Elasticsearch filter multiple fields


(Siv) #1

I have following data set indexed in my elasticsearch

{
"title": "Professor",
"class": [6001, 6015, 6018],
"subject": [5010, 5012, 5013],
"salary": 12500
}

{
"title": "Professor",
"class": [6012, 6013, 6014],
"subject": [5010, 5005, 5004],
"salary": 16600
}

{
"title": "Principal",
"class": [7001, 7010, 6018],
"subject": [5010, 5012, 5013],
"salary": 14750
}

{
"title": "Asst Professor",
"class": [6012, 6013, 6014],
"subject": [5010, 5005, 5004],
"salary": 16600
}
I'm trying to search

class - 6001 OR 6018 OR 6013 AND subject - 5013 OR 5004 AND salary (range) - 12000 to 15000

I'm using below query

{
"query" : {
"filtered" : {
"filter" : {
"bool" : {
"must" : [
{ "term" : {"class" : [6001, 6018, 6013]}},
{ "term" : {"subject" : [5013, 5004]}},
{"range" : {"salary" : {"gte": 12000,"lte": 15000}}}
]
}}}}}

But I'm not getting the result that Im expecting, what is wrong in this?


(Ivan Brusic) #2

Try using a Terms filter instead of Term. More flexibility.

https://www.elastic.co/guide/en/elasticsearch/reference/1.6/query-dsl-terms-filter.html

Cheers,

Ivan


(Siv) #3

Thank you... I want to apply AND between terms? I tried the below but it doesnt apply.

{
"query" : {
"filtered" : {
"filter" : {
"bool" : {
"and" : [
{ "terms" : {"class" : ["6001", "6018"]}},
{ "terms" : {"subject" : ["5013"]}},
{ "range" : {"salary" : {"gte": 12000,"lte": 15000}}}
]
}}}}}


(Colin Goodheart-Smithe) #4

Have a look at the documentation for the bool filter for an example you can look at and the docs for the bool query for an explanation of what the different clause types mean. In your example above you will probably want to use must clauses.


(Siv) #5

Hi

I have written the below, but it returns all data insted of specific result. Anything wrong in this? I want extract data in which Class has to be 7001 OR subject should be 5012 AND subject should not be 5013

{
"query" : {
"filtered" : {
"filter" : {
"bool" : {
"must" : [
{ "term" : {"class" : "7001"}},
{ "term" : {"subject" : "5012"}}
],
"must_not" : {
"term" : {"subject" : "5013"}
}
}
}
}
}
}


(Ayush Sangani) #6

I believe you may want to use should clause inside must clause that will give you basically OR flavor in your must clause.


(system) #7