How to write AND Query in Elasticsearch?

Document 1

{
"userid" : 1234,
"username" : "Sigehere Smith",
"type" : "student",
"department" : {
"deptname" : "Computer Science",
"deptpath" : ["First" , "Second"]
}
}

Document 2

{
"userid" : 1235,
"username" : "Rayan Smith",
"type" : "teacher",
"department" : {
"deptname" : "Computer Science",
"deptpath" : ["Four" , "Second"]
}
}

Document 3

{
"userid" : 1237,
"username" : "Lucky Smith",
"type" : "teacher",
"department" : {
"deptname" : "Computer Science",
"deptpath" : ["Four" , "First"]
}
}

I want to retrive that document. that contains following information.

   "department" : {
           "deptname" : "Computer Science",
          "deptpath" : "second"
    }

How will i write and query on above data.

Use a Bool query with must or filter clauses.
Must if relevancy is important. Filter if it's not.

1 Like

Thanks For your response.

I have tried following query: I want to apply AND operator in that query to retrive those document that department name is Computer Science AND department path contains term "Second".
curl -XGET 'http://192.168.1.2:9200/records/_search' -d'{
"query": {
"bool": {
"must": [
{
"match":
{
"department.deptname" : "Computer Science"
}
},
{
"match":
{
"department.deptpath" : "Second"
}
}
]
}
}
}'

1 Like

This looks correct to me. Just be careful with the analyzers you are using.

Might not work as you would expect.

BTW, I'd use filter instead of must here.

1 Like

Yes It gives me all record. It will not full fill my requirement because match doesn't apply on department object it just applies on document, It will retrive all document that contains department name is Computer Science or department path "Second".

Can you please give me suggestion how will i write correct query for object.

1 Like

Can you send a full script which I can use as a basis?

1 Like