Nick Nick
Nick Nick

Reputation: 23

matching two string arrays in elasticsearch

I am new in elasticsearch, and have field:tags["tag1","tag2","tag3","color2","color1"] in elasticsearch.

I am about to match my array of tags with field tags in db ,so that 50% of tags minimum is matching.

{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "tags": [
              "tag1",
              "tag2",
              "tag3"
            ],
            "boost": 1.0
          }
        }
      ],
      "adjust_pure_negative": true,
      "minimum_should_match": "50%",
      "boost": 1.0
    }
  }
}

it is not working

Upvotes: 2

Views: 56

Answers (1)

Amit
Amit

Reputation: 32376

You need to add different should clause in order percentage attribute to work, adding below sample example similar to what you have to show:

Index mapping

{
    "mappings": {
        "properties": {
            "tags": {
                "type": "text"
            }
        }
    }
}

Index sample doc

{
  "tags" : ["tag1", "tag2", "tag3", "tag4", "tag5"]
}

search query which has more than 50% matching tag returning doc

{
  "query": {
    "bool" : {
      "should" : [
        { "term" : { "tags" : "tag1" } },
        { "term" : { "tags" : "tag2" } },
        { "term" : { "tags" : "tag3" } },
        { "term" : { "tags" : "tag8" } }
      ],
      "minimum_should_match" : "50%",
      "boost" : 1.0
    }
  }
}  

Search result

"hits": [
      {
        "_index": "tags",
        "_type": "_doc",
        "_id": "1",
        "_score": 1.0,
        "_source": {
          "tags": [
            "tag1",
            "tag2",
            "tag3",
            "tag4",
            "tag5"
          ]
        }
      }

Sample where it won't bring search result for 50%

{
  "query": {
    "bool" : {
      "should" : [
        { "term" : { "tags" : "tag1" } },
        { "term" : { "tags" : "tag6" } },
        { "term" : { "tags" : "tag7" } },
        { "term" : { "tags" : "tag8" } }
      ],
      "minimum_should_match" : "50%",
      "boost" : 1.0
    }
  }
}

Upvotes: 1

Related Questions