0

I want to search with two fields in ElasticSearch, fields are:

1) SearchTerm (Textfield)

2) City (Textfield)

If I use mysql Query would be:

if both has value

select * from table where term = 'abc' AND city = 'mexico'

if only term has value

select * from table where term = 'abc'

if only city has value

select * from table where city = 'mexico'

How can I use this in ElasticSearch I'm trying with the following:

"bool" : {
"should": [
    { 
    "multi_match": {
        "query":   '"'+term.toLowerCase()+'"',
        "fields": 
        [ 
                "title", "desc" 
        ],
        "operator" : "and"
    }
    }, 
    { 
    "wildcard": {
        "city": {
            value: city.toLowerCase()
        }
    }
    }  
],
}

Please help

Thanks

Randheer

2 Answers2

2

And conditions can be modeled with a must clause in your bool query

Edit: I understood your question and your city query is not right it should be:

{
  "bool": {
    "should": [{
        "multi_match": {
          "query": '"' + term.toLowerCase() + '"',
          "fields":
          [
            "title", "desc"
          ],
          "operator": "and"
        }
      }, {
        "wildcard": {
          "city": city.toLowerCase()
        }
      }
    ]
  }
}
MartinSchulze
  • 889
  • 1
  • 7
  • 14
1

Bool query with must clause(Using curl):-

1.) select * from table where term = 'abc' AND city = 'mexico'

curl -XGET 'localhost:9200/indexName/_search?pretty&size=50' -H 'Content-Type: application/json' -d'      {
"query":{
  "bool":{
    "must":[
      {
       "term":{ "city":"mexico" }
      },
      {
       "term":{ "term":"abc" }
      }
     ]
   }
  }
}';

2.) select * from table where term = 'abc'

curl -XGET 'localhost:9200/indexName/_search?pretty&size=50' -H 'Content-Type: application/json' -d'  {
 "query":{
   "bool":{
     "must":[{
       "term":{ "term":"abc" }
     }]
   }
 }

}';

3.) select * from table where city = 'mexico'

curl -XGET 'localhost:9200/indexName/_search?pretty&size=50' -H 'Content-Type: application/json' -d'   {
 "query":{
   "bool":{
     "must":[{
       "term":{ "city":"mexico" }
     }]
   }
 }
}';

for more details find here:- https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

NeeruKSingh
  • 1,545
  • 3
  • 22
  • 26