Home > Mobile >  Elastic Search Json field query with number key
Elastic Search Json field query with number key

Time:01-05

How can I query elastic search based on the number key?

JSON field name years_of_experience :

"{\"61\": \"10\", \"8240\": \"5\", \"8249\": \"2\", \"50\": \"0\", \"2079\": \"2\"}"

I want to filter years_of_experience like 50:0.

CodePudding user response:

So, according to your sample, you have documents like the below:

POST myindex/_doc
{
  "years_of_experience": {
    "50": "0",
    "61": "10",
    "2079": "2",
    "8240": "5",
    "8249": "2"
  }
}

So, you have an object for years_of_experience, and you want to do an exact match with the field name and values. You need to set all fields inside this field you want to set as a keyword type. First, you need to handle the mapping part of this problem. Here is a solution for this :

PUT myindex
{
  "settings": {
    "number_of_shards": 1,
    "number_of_replicas": 0
  },
  "mappings": {
    "dynamic_templates": [
      {
        "strings_as_keyword": {
          "match_mapping_type": "string",
          "path_match": "years_of_experience.*",
          "mapping": {
            "type": "keyword"
          }
        }
      }
    ],
    "properties": {
      "years_of_experience": {
        "type": "object"
      }
    }
  }
}

While creating your index for this data, you need to use a dynamic template for the years_of_experience object. And all the fields inside this will be keyword type, and you can run term queries on these fields.

So now we can create the documents after creating an index with the above settings. And you can filter the data as below :

GET myindex/_search
{
  "query": {
    "term": {
      "years_of_experience.50": "0"
    }
  }
}
  • Related