Reputation: 303
I need to make a query in Elasticsearch which returns documents only if all of the words from a search text are found not matter in which field. For example:
searchText = "term1 term2 term3 term4"
fields = ['field1', 'field2', 'field3', 'field4', 'field5', 'field6']
If all words from searchText are in any field from 1 to 6, then return the documents. Else return nothing. Thanks!
This kind of document should be returned:
searchText = 'We need to change ourselves'
fields = [
field1: "We are happy.",
field2: "change ourselves",
field3: "You are the one I need"
field4: "to be",
field5: "irrelevant",
field6: ""
]
but not this one (not found: We
, ourserves
):
searchText = 'We need to change ourselves'
fields = [
field1: "I am happy.",
field2: "change",
field3: "You are the one I need"
field4: "to be",
field5: "irrelevant",
field6: "something"
]
Upvotes: 0
Views: 127
Reputation: 16182
You can use multi_match with AND operator
{
"query": {
"multi_match": {
"query": "term1 term2 term3 term4",
"fields": [
"field1",
"field2",
"field3",
"field4",
"field5",
"field5"
],
"operator": "AND"
}
}
}
Update 1:
As already answered by @Razvan Theodor, cross_fields will enable search of query words spread across multiple fields
Modified query will be
{
"query": {
"multi_match": {
"query": "term1 term2 term3 term4",
"fields": [
"field1",
"field2",
"field3",
"field4",
"field5",
"field5"
],
"operator": "AND",
"type": "cross_fields" // note this
}
}
}
Upvotes: 1
Reputation: 303
Found the solution:
"query": {
"multi_match": {
"query": "term1 term2 term3 term4",
"type": "cross_fields",
"operator": "and",
"fields" => {
"field1",
"field2",
"field3",
"field4",
"field5",
"field6"
}
}
}
Upvotes: 0