1

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.

2
  • Could you give more detail? What does it mean to filter of year?of_experience. I can write to you an answer as "use painless script" :) you can get the more detailed answer but if you can give more details Commented Jan 3, 2023 at 6:20
  • I have some data in elastic search which has one JSON field named years_of_experience. like. "{\"61\": \"10\", \"8240\": \"5\", \"8249\": \"2\", \"50\": \"0\", \"2079\": \"2\"}" Now I want to query years_of_experience with key and value. query years_of_experience based on 50 as the key and 0 as the value. Commented Jan 3, 2023 at 8:56

1 Answer 1

1

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"
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.