Skip to content
Advertisement

How to search by dict keys in ElasticSearch

I am new in elasticsearch and I need to write query described below

I have an elasticsearch index with documents like this one

Numbers mean entries of words in book

{
  "words": {        # words listed below are different in every document
    "cat": 7,
    "monkey": 4,
    "mouse": 10,
    ...
}

I want to search documents by words “cats” (not “cat”), “monkey” and e.g “mous”. How do I write query that will find “cat”, “monkey” and “mouse” in document and consider their values in counting score?

upd. Example: I have documents

{                             # doc1
    "words": {        
        "cat": 7,
        "monkey": 4,
        "mouse": 10,
    }
}
{                             # doc2
    "words": {        
        "Cat": 20,
        "monkeys": 40,
        "mouse": 10,
    }
}
{                             # doc3
    "words": {        
        "Dog": 10,
        "monkey": 2,
        "human": 10,
    }
}
# I am searching by words "cats", "monkey", "mouse"
# I want to get doc2 as the most relevant result (because of words matches and entries quantity). 
# doc1 should be the second result (words do match, but there are less entries). 
# doc3 is the third result (too few words matches)

Any ideas?

Advertisement

Answer

I don’t know if I understand correctly but you want to search for “cats” and return the doc words with the words “cat”, “monkey” and “mouse”.

Run this example I made and see if it works for you.

PUT my-index-000001
{
      "mappings" : {
      "properties" : {
        "words" : {
          "properties" : {
            "count" : {
              "type" : "text"
            },
            "key" : {
              "type" : "text",  
              "analyzer": "english"
            }
          }
        }
      }
    }
}

POST  my-index-000001/_doc/1
{
  "words": [
    {
      "key": "cat",
      "count": "7"
    },
    {
      "key": "monkey",
      "count": "4"
    },
    {
      "key": "mouse",
      "count": "10"
    }
  ]
}

GET my-index-000001/_search
{
  "query": {
    "match": {
      "words.key":{
        "query": "cats"
      }
    }
  }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement