Searching multiple values in multiple fields

Hi folks.

I have an index with documents that have a product_id (long) and product_subtype (text). I'm trying to search for documents using multiple product_ids and product_subtypes.

The data that I have is this:

[
    {
        "id": 1,
        "product_id": 123,
        "product_subtype": "subtype abc"
    },
    {
        "id": 2,
        "product_id": 123,
        "product_subtype": "subtype def"
    },
    {
        "id": 3,
        "product_id": 456,
        "product_subtype": "subtype abc"
    },
    {
        "id": 4,
        "product_id": 789,
        "product_subtype": "subtype abc"
    },
    {
        "id": 5,
        "product_id": 789,
        "product_subtype": "subtype def"
    }
]

I want to search for products with product_subtype = "subtype abc" OR product_subtype = "subtype def", and that belong to product_id 123 OR 456.
The result I expect is ids 1, 2 and 3 from the data above.

My initial approach was to do this query, but this also returns ids 4 and 5:

{
    "query": {
        "bool": {
            "should": [
                { "match_phrase": { "product_subtype": "subtype abc" } },
                { "match_phrase": { "product_subtype": "subtype def" } },
                { "terms": { "product_id": [123, 456] } }
            ]
        }
    }
}

I then tried to move the product_id part to must instead of should. This works if I query for both product_subtypes (abc and def), but if I query for just abc, it still returns results for def (although now respecting the product_ids):

{
    "query": {
        "bool": {
            "should": [
                { "match_phrase": { "product_subtype": "subtype abc" } },
                { "match_phrase": { "product_subtype": "subtype def" } }
            ],
            "must": [
                { "terms": { "product_id": [123, 456] } }
            ]
        }
    }
}

The last thing I tried was moving everything to must, but then it doesn't return anything.

Is there a way that I could accomplish this query with ES?

Thanks in advance

Guess I solved my own problem with this query below:

{
    "query": {
        "bool": {
            "must": [
                { "terms": { "product_id": [123, 456] } },
                {
                    "bool": {
                        "should": [
                            { "match_phrase": { "product_subtype": "subtype abc" } },
                            { "match_phrase": { "product_subtype": "subtype def" } }
                        ]
                    }
                }
            ]
        }
    }
}

@brsntus
You may want to use filter instead of must and { "term": { "product_subtype.keyword" : "subtype abc"} } instead of match_phrase. I am assuming product_subtype has keyword as subfield.

Your match_phrase will also match " foo subtype abc def"

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.