Search code examples
elasticsearchelasticsearch-6

Filters with dynamic fields in elasticsearch


I am switching a very old version of ElasticSearch to version 6.5.

...  
  "text_mined_entities": {
            "nlp": {
                "abbreviations": [],
                "chunks": [],
                "recurring_chunks": [],
                "tagged_entities_grouped": {
                    "NEURO|SCICRUNCH": [
                        {
                            "category": "NEURO",
                            "end": 41,
                            "label": "Infant",
                            "match": "infant",
                            "original_value": "Infant",
                            "reference": "BIRNLEX695",
                            "reference_db": "SCICRUNCH",
                            "sentence": 0,
                            "start": 35
                        },
...

I am wanting to filter on the text_mined_entities.nlp.tagged_entities_grouped.*.reference fields ( which are stored as 'keyword' ), but haven't had much luck. Something like:

GET _search
{
  "query": {
    "bool": {
      "filter": { "term": {
        "text_mined_entities.nlp.tagged_entities_grouped.*.reference": "BIRNLEX695"

      }}

    }
  }
}

Any suggestions? Thanks.


Solution

  • Wildcard on fields can't be applied on term query. Instead you can use query_string which supports wildcard on field as well. So following will work:

    Assuming text_mined_entities and nlp are of type nested

    {
      "query": {
        "nested": {
          "path": "text_mined_entities.nlp",
          "query": {
            "query_string": {
              "query": "BIRNLEX695",
              "fields": [
                "text_mined_entities.nlp.tagged_entities_grouped.*.reference"
              ]
            }
          }
        }
      }
    }
    

    Update (if text_mined_entities & nlp are object type and not nested):

    {
      "query": {
        "query_string": {
          "query": "BIRNLEX695",
          "fields": [
            "text_mined_entities.nlp.tagged_entities_grouped.*.reference"
          ]
        }
      }
    }