how to search a document in elastic if two documents contains same word?

Viewed 97

I have following two documents in elastic:

Document-1

{"name":"doc1","tags":["Hello World"]}

Document-2

{"name":"doc2", "tags":["World"]}

I want to search a document which contains "World" as single word in documents but this query returns both documents:

{"query":{"bool":{"must":[{"match":{"tags":{"query":"World"}}}]}}}

How can I achieve this?

2 Answers

If you mapping has keyword for tags field, you can use it such as

GET your_index/doc
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "tags.keyword": { // use `keyword` field here
              "query": "World"
            }
          }
        }
      ]
    }
  }
}

Only if your mapping has it as below

{
  "your_index": {
    "mappings": {
      "doc": {
        "properties": {
          "name": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "tags": {
            "type": "text",
            "fields": {
              "keyword": { 
                "type": "keyword", // this mapping is required
                "ignore_above": 256
              }
            }
          }
        }
      }
    }
  }
}

you need to use keyword Analyzer

curl -X PUT "http://localhost:9200/my_index" -H 'Content-Type: application/json' -d'
{
  "settings": {
    "analysis": {
      "analyzer": {
        "my_analyzer": { 
          "type": "custom",
          "tokenizer": "keyword"
        }
      }
    }
  },
  "mappings": {
    "_doc": {
      "properties": {
        "filedname": {
          "type": "text",
          "analyzer": "my_analyzer" 
        }
      }
    }
  }
}'
Related