xiGUAwanOU
xiGUAwanOU

Reputation: 334

Restrict searching result with matches of multiple fields in ElasticSearch

I'm trying to restrict the searching result with more than one searching words in different document fields.

For example, I have 3 fields field1, field2 and field3 and two searching words word1 and word2. I'd like to have all the documents with any two of the fields matching these words separately, e.g.:

How should I write the query?

Btw. I'm using ElasticSearch 5.x.

Upvotes: 0

Views: 241

Answers (2)

Adam T
Adam T

Reputation: 1701

I think this should work:

{
    "query": {
        "bool": {
            "must": [{
                    "multi_match": {
                        "query": "word1",
                        "fields": ["field1", "field2", "field3"]
                    }
                },
                {
                    "multi_match": {
                        "query": "word2",
                        "fields": ["field1", "field2", "field3"]
                    }
                }
            ]
        }
    }
}

Upvotes: 1

LeBigCat
LeBigCat

Reputation: 1770

Please read documentation: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

{
    "query": {
        "bool": {
            "should": [
                {
                    "bool": {
                        "must": [
                            {"term": {"field1 ": "word1"}},
                            {"term": {"field3 ": "word2"}}
                        ]
                    }
                },
                {
                    "bool": {
                        "must": [
                            {"term": {"field2 ": "word1"}},
                            {"term": {"field3 ": "word2"}}
                        ]
                    }
                },
                {
                    "bool": {
                        "must": [
                            {"term": {"field1 ": "word2"}},
                            {"term": {"field2 ": "word1"}}
                        ]
                    }
                }
            ]
        }
    }
}

Upvotes: 0

Related Questions