Ernesto
Ernesto

Reputation: 4017

Filtering a multi_match query in elasticsearch by another field

I'm trying to perform a search with ElasticSearch, that must match some search terms in the sections index, but only for sections that belong to certain projects, namely, the projects to which the current user has access.

So I'm trying to apply a filter to the query, so that it will filter sections that have the project_id included in a small set of 2 or 3 different values. If a section's project_id is among the valid project_id's, it should be included. Otherwise it won't.

This is all in the context of a rails api using the elasticsearch-model gem.

This is the query I'm passing in. It pretends to filter sections, so that only sections in projects 2 and 5 are included in the results.

{
  "query": {
    "filtered": {
      "query": {
        "multi_match": {
          "query": "search terms here",
          "type": "cross_fields",
          "fields": ["title^3", "contents"],
          "operator": "and"
        }
      },
      "filter": {
        "or": {
          "filters": [
            { "exists": { "project_id": 2 } },
            { "exists": { "project_id": 5 } }
          ]
        }
      }
    }
  }
}

And I get this error:

QueryParsingException[[sections] [exists] filter does not support [project_id]]

Any ideas?

Upvotes: 2

Views: 3416

Answers (1)

BlackPOP
BlackPOP

Reputation: 5737

The exist filter means checking the fields is exist or not.refer.

To get what you trying to achieve.

 {
 "query": {
  "filtered": {
     "query": {
        "multi_match": {
           "query": "search terms here",
           "type": "cross_fields",
           "fields": [
              "title^3",
              "contents"
           ],
           "operator": "and"
        }
     },
     "filter": {
        "terms": {
           "project_id": ["1","2"]
        }
      }
    }
  }
}

HOpe it helps..!

Upvotes: 8

Related Questions