Stono
Stono

Reputation: 2337

Elasticsearch Array Comparison

I'm new to elasticsearch, so be kind.

I'm trying to store and query data, which is tagged with N number of tags. I want to compare a search query array with the stored array and return the results in order of which items match the most tags.

Dataset example:

{ name: "karl", tags: ["terrible", "programmer"] }
{ name: "bob", tags: ["awesome", "programmer"] }

Query example, matching both people:

query: { tags: ["programmer"] }
result: [karl, bob]

And in this example, both are returned but bob scores high, because more tags were matched, Karl is still shown though, despite not matching on awesome.

query: { tags: ["programmer", "awesome"] }
result: [bob, karl]

The closet I have got is this, however it doesn't seem to score bob higher than karl

{
  "query": {
    "bool": {
      "should": [
        { "match": { "tags": "programmer" } },
        { "match": { "tags": "awesome" } }
       ],
      "minimum_number_should_match": 1
    }
  }
}

Would love some support :-) Thanks!

Upvotes: 4

Views: 2012

Answers (2)

Claudio
Claudio

Reputation: 652

If you need to have only the document that match both (or even more) tags, you need to use a must query (https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html) Your query looks like:

{
  "query": {
    "bool": {
      "must": [
        { "match": { "tags": "programmer" } },
        { "match": { "tags": "awesome" } }
       ]
    }
  }
}

Upvotes: 0

Joe - Check out my books
Joe - Check out my books

Reputation: 16933

It does score bob significantly higher than karl: enter image description here

If you wanna match both of the tags, increase the minimum operator: enter image description here

Which is essentially the same as a bunch of bool-musts:

GET karl/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "tags": "programmer"
          }
        },
        {
          "match": {
            "tags": "awesome"
          }
        }
      ]
    }
  }
}

Upvotes: 2

Related Questions