I have two distinct query, and I want to combine them with an 'OR'/'AND' in between. How do I do that?
For example, for the given queries I just want to run Query1 OR Query2 in the elasticsearch.
Query1:
{
"query": {
"filtered": {
"query": {
"query_string":{
"query":"Batman",
"default_operator":"AND",
"fields"::[
"Movies._all"
]
}
},
"filter": {
"bool": {
"must": [
{
"query":{
"filtered":{
"filter":{
"and":[
{
"term":{
"cast.firstName":"Christian "
}
},
{
"term":{
"cast.lastName":"Bale"
}
}
]
}
}
}
}
]
}
}
}
}
}
Query2:
{
"query": {
"filtered": {
"query": {
"query_string":{
"query":"Dark Knight",
"default_operator":"AND",
"fields"::[
"Movies._all"
]
}
},
"filter": {
"bool": {
"must": [
{
"query":{
"filtered":{
"filter":{
"and":[
{
"term":{
"director.firstName":"Christopher"
}
},
{
"term":{
"director.lastName":"Nolan"
}
}
]
}
}
}
}
]
}
}
}
}
}
You can combine the queries using bool query. Based on your requirement you can use 'should' or 'must' inside the bool clauses. You may want to schearch for both the field you want, and then aggregate by the most important field.
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.
must means: Clauses that must match for the document to be included. should means: If these clauses match, they increase the _score ; otherwise, they have no effect. They are simply used to refine the relevance score for each document.
compound query A query that uses set operators (UNION, UNION ALL, INTERSECT, or MINUS) to combine two or more simple or complex statements. Each simple or complex statement in a compound query is called a component query.
You need to use a bool query Something like below will work fine -
{
"query" : {
"bool" : {
"must" : [
{ // Query1 },
{ // Query2}
]
}
}
}
Use must for AND and should for OR
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