0

I have some docs in elastic search

doc1 -> name: name1  
doc2 -> name: name1, otherprop: prop1  
doc3 -> name: name1, otherprop: prop1, otherprop2: prop2  

My goal is get doc1 by name but the query return all three docs
I tried to get doc1 by name and min(count of properties) but my query is return or nothing or all match documents

{
  "query": {
    "bool": {
      "filter": [
        { "term": { "name": "name1"   }}
      ]
    }
  },
  "aggs": {
    "models": {
      "terms": { "field": "name" } 
    }
  }
}

How can I get only doc1 with my idea?
Thanks

user1392853
  • 269
  • 1
  • 6
  • 19

1 Answers1

1

To achieve such a feature you can add number of fields during index time and check the number of fields during your query, to update all of your documents you can use this update by query:

Update by query

POST [index name]/_update_by_query
{
    "query": {
        "match_all": {}
    }, 
    "script": {
       "source": "ctx._source.fieldsCount = ctx._source.size()"
    }
}

Then you can use FieldsCount field to write your query.

Kaveh
  • 1,158
  • 6
  • 16
  • Hi @Kaveh But other props are unpredictable, they can be 2 or 3 or more fields – user1392853 Jun 08 '21 at 04:36
  • If you don't name of fields maybe it is better to add a field to include number of fields in your document and use that field to query, another option can be use of runtime fields during query you can check it here: https://www.elastic.co/guide/en/elasticsearch/reference/7.13/runtime-search-request.html. – Kaveh Jun 08 '21 at 09:06
  • I updated my answer to include a solution to add number of fields during indexing. – Kaveh Jun 08 '21 at 09:12