Antoine Cld
Antoine Cld

Reputation: 59

Elasticsearch Bool query

I want to filter Product with 2 field, Category and Brand_id.

Category:

 Product.__elasticsearch__.search  query: { match:  { category: "Pulls & Gilets" } }

I got a total of 116

Brand_id:

Product.__elasticsearch__.search  query: { match:  { brand_id: "1" } }

I got a total of 4

Both:

Product.__elasticsearch__.search query: {
                  bool: {
                    must: {
                      term: { brand_id: "1" }
                    },
                    must: {
                      term: { category: "Pulls & Gilets" }
                      }
                    }
                  }

I should have a total of 4 and I got 0. I've tried with "filter" instead of "must" but same result. Thanks

Upvotes: 0

Views: 504

Answers (1)

Branel Moro
Branel Moro

Reputation: 132

When you index your data into elasticsearch, it uses standard analyzer to split string and it generates lowercase tokens in inverted index - https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-standard-analyzer.html. So for text "Pulls & Gilets", this analyzer will generate three tokens - "pulls", "&" and "gilets" in inverted index.

Match query is full text query and it uses field analyzer before comparing any string.

So { match: { category: "Pulls & Gilets" } } will generate three lowercase tokens - "pulls", "&" and "gilets" and it will fetch all documents having any one of these - "pulls", "&" and "gilets"

Hence you are getting more number of documents having any one of these - "pulls", "&" and "gilets" tokens for category field.

Term query directly compares with tokens generated at time of indexing. But in term query you are sending normal text like {term: { category: "Pulls & Gilets" }}. And there is no such token like "Pulls & Gilets" generated for any of document as it string is analized using standard analyzer. Hence you are getting 0 documents.

Ideally you should send all tokens in lowercase like - {terms: { category: ["pulls", "&", "Gilets"] }}

This will fetch all documents with category having tokens "pulls", "&" or "Gilets"

Upvotes: 1

Related Questions