bsgrd
bsgrd

Reputation: 663

Elasticsearch filter with multi_match

I'm trying to write a query in ElasticSearch where I combine multi_match with filter for an id or a number og ids.

This is what i have so far:

{
    "query": {
        "bool": {
            "must": {
                "multi_match": {
                    "query": "Kasper",
                    "fields": ["name", "first_name", "last_name"]
                }
            },
            "filter": {
                "term": {
                    "user_id": "ea7528f0-1b8a-11e8-a492-13e39bbd17cb"
                }
            }
        }
    }
}

The "must" part of the query works perfectly, and when I run it alone, I get two results. When I pick out the "user_id" from one of the two results and adds the "filter" part of the query with that id, I get nothing.

What I really want to do is have something like in SQL where user_id in ('id1', 'id2'), so the filtering would be something like:

...,
"filter": {
    "terms": {
        "user_id": ["ea7528f0-1b8a-11e8-a492-13e39bbd17cb"]
    }
}

Did I misunderstand something here?

Upvotes: 2

Views: 3357

Answers (1)

Piotr Pradzynski
Piotr Pradzynski

Reputation: 4535

I'm guessing that this is because user_id field is treated as a text and is analyzed. You should use keyword type in this situation (you need just change the mapping of user_id field.

Another way (if you are on Elasticsearch 5+) you can search in keyword subfield. Just try use below query:

{
  "query": {
    "bool": {
      "must": {
        "multi_match": {
          "query": "Kasper",
          "fields": ["name", "first_name", "last_name"]
        }
      },
      "filter": {
        "term": {
          "user_id.keyword": "ea7528f0-1b8a-11e8-a492-13e39bbd17cb"
        }
      }
    }
  }
}

I only changed "user_id" to "user_id.keyword" in your query.

Upvotes: 7

Related Questions