I am trying to build a query that will find all user documents (docType = user)
and then filter them based on many filters. Such as location, gender, age, etc. The filters are added / removed based on user input on the search function I'm building.
Below returns no results:
{
"query": {
"filtered": {
"query": {
"match_all": {}
},
"filter": {
"and": {
"filters":
[
{
"term": {
"doc.docType": "user"
}
},
{
"term": {
"doc.data.profile.location" : "CA"
}
}
]
}
}
}
}
}
Below return results:
{
"query": {
"filtered": {
"query": {
"field": {
"doc.data.profile.location" : "CA"
}
},
"filter": {
"and": {
"filters":
[
{
"term": {
"doc.docType": "user"
}
}
]
}
}
}
}
}
The latter, although returning results, isn't going to work in the long run as I may want to include an extra filter for age, gender, etc and I can't seem to add multiple fields. The first query works if I remove the filter for location.
One of the most common queries in elasticsearch is the match query, which works on a single field. And there's another query with the very same options that works also on multiple fields, called multi_match. These queries support text analysis and work really well.
Joining queriesedit Instead, Elasticsearch offers two forms of join which are designed to scale horizontally. Documents may contain fields of type nested . These fields are used to index arrays of objects, where each object can be queried (with the nested query) as an independent document.
Here is how you can write multiple filter query
{
"query": {
"bool": {
"filter": [
{
"term" : {
"id":254
}
},
{
"term" : {
"cityId":35
}
}
],
"must": [
{
"match_all": {}
}
]
}
}
}
The bool filter allows you to chain multiple MUST
, SHOULD
and SHOULD_NOT
requests together. Allowing for you to construct this into one query.
I think what you want is a bool query
That way you can chain multiple musts together to get the desired result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With