shicholas
shicholas

Reputation: 6153

Multiple types in Elasticsearch Type Filter

I have a filtered query like this

query: {
  filtered: {
    query: {
      bool: {
        should: [{multi_match: {
                    query: @query,
                    fields: ['title', 'content']
                    }
                  },{fuzzy: {
                     content: {
                       value: @query,
                       min_similarity: '1d',
                       }
                 }}]
               }
             },
    filter: {
      and: [
         type: {
            value: @type
          }]
    }}}

That works fine if @type is a string, but does not work if @type is an array. How can I search for multiple types?

Upvotes: 2

Views: 4389

Answers (3)

jakxnz
jakxnz

Reputation: 550

This worked for me:

Within the filter parameter, wrap multiple type queries as should clauses for a bool query

e.g

{
  "query": {
    "bool": {
      "must": {
        "term": { "foo": "bar" }
      },
      "filter": {
        "bool": {
          "should": [
            { "type": { "value": "myType" } },
            { "type": { "value": "myOtherType" } }
          ]
        }
      }
    }
  }
}

Suggested by dadoonet in the Elasticsearch github issue Support multiple types in Type Query

Upvotes: 1

Alex Brasetvik
Alex Brasetvik

Reputation: 11744

You can easily specify multiple types in your search request's URL, e.g. http://localhost:9200/twitter/tweet,user/_search, or with type in the header if using _msearch, as documented here.

These are then added as filters for you by Elasticsearch.

Also, you usually want to be using bool to combine filters, for reasons described in this article: all about elasticsearch filter bitsets

Upvotes: 2

shicholas
shicholas

Reputation: 6153

This worked, but I'm not happy with it:

filter: {
  or: [
    { type: { value: 'blog'} },
    { type: { value: 'category'} },
    { type: { value: 'miscellaneous'} }
  ]
}

I'd love to accept a better answer

Upvotes: 3

Related Questions