1
votes

I am working on elasticsearch and using term in search query. Please have a look on sample indexed data below:

"_source": {
    "type": "ITEM",
    "primaryKey": "3923",
    "displayName": "Lumia 505",
    "attributes": {
        "n26273": "Lumia 505",
        "n26275": "Mobile"
    },
    "mappings": {
        "Primary Hierarchy": [
            "Nokia"
        ]
    }
}

For searching data against my any search text I am using below query which is working fine:

{
   "query":{
      "bool":{
         "must":[
            {
               "query_string":{
                  "query":"----MySearchTextHere----",
                  "default_operator":"AND"
               }
            },
            {
               "term":{
                  "type":"item"
               }
            }
         ]
      }
   },
   "size":10,
   "from":0
}

Queries:

1. How can I add term in query to search against field "mappings.Primary Hierarchy" which is an array?

2. How can I achieve #1 without mentioning nested field name as nested field name would be dynamic? only field name mappings is constant.

1

1 Answers

0
votes

There is no problem in referring nested field ("mappings.Primary Hierarchy" in your case) in term query

{
   "query":{
      "bool":{
         "must":[
            {
               "query_string":{
                  "query":"Nokia",
                  "default_operator":"AND"
               }
            },
            {
               "term":{
                  "mappings.Primary Hierarchy":"nokia"
               }
            }
         ]
      }
   },
   "size":10,
   "from":0
}

this would just successfully filter by Nokia. If you want to use exactly Nokia (not anaylyzed term), you should use "mappings.Primary Hierarchy.keyword" field. Keyword here means, that the content of this field is exactly as it was passed by you during indexing.

2nd thing is also possible but would require proper mappings. You need to specify, that your mappings is a nested type (which means there could be other fields in it).

Simple example in your case could be something like this:

{
    "mappings": {
        "_doc" : {
            "properties" : {
                "mappings" : {
                    "type" : "nested"
                }
            }
        }
    }
}

You need to create your index with these settings applied.

In this case your query could look like this:

{
  "query": {
    "nested": {
      "path": "mappings",
      "query": {
        "multi_match": {
          "query": "Nokia"
        }
      }
    }
  }
}

Multi match query with no fields specified will be defaulted to all fields under mappings objects