4

I have one problem regarding elastic search, I want to search the exact match in the filters. For example, If the color filter is applied only "Black" then the elastic search should be returned only "Black" products instead of other products which have Black keywords in their product color like "Black grey". I have tried "match_phrase" instead of "match" but couldn't get anything.

Please check the screenshot of my JSON string: https://www.screencast.com/t/wjCcpfQwTxw

enter image description here Thanks in advance

2 Answers2

8
You can user term query.
For example: 
GET {Your index}/_search
{
    "query": {
        "term": {
            "color.keyword": {
                "value": "Black"
            }
        }
    }
}

It will return the documents which 'color' field equals to Black.If your color field is text type.Remember add '.keyword' after it.
user9940960
  • 134
  • 4
  • 2
    .keyword did the job for me – Diego Ponciano Aug 04 '20 at 18:09
  • 1
    I don't have any joy with adding .keyword to an existing field, I get no results for the query. Is there some configuration to enable the use of this implicit keyword? I found that I can add .anything to a field name in this kind of query and the API does not throw an error. It just fails to return any results. – julianhatwell May 25 '21 at 12:57
-1

To get an exact match use the type keyword for the field color. Here is an example with curl. Tested with Elasticsearch 7.3

  1. Create an Index

    curl -X PUT "localhost:9200/products?pretty" -H 'Content-Type: application/json' -d' {} '

  2. Define an mapping for the field color of type keyword.

    curl -X PUT "localhost:9200/products/_mapping?pretty" -H 'Content-Type: application/json' -d' { "properties": { "color": { "type": "keyword" } } } '

  3. Add two sample data sets

    *curl -X PUT "localhost:9200/products/_doc/1?pretty" -H 'Content-Type: application/json' -d' { "color" : "blue green" } '

    curl -X PUT "localhost:9200/products/_doc/2?pretty" -H 'Content-Type: application/json' -d' { "color" : "blue" } '*

  4. Test the query.

    curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d' { "query": { "match": { "color": "blue" } } } '