Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search on multiple fields with Elasticsearch

I'm new to Elasticsearch and I'm wondering how I can make a search specifing one or more fields.

With SQL I would write this query:

"SELECT field1, field2, field3 FROM tablename WHERE field1 = 'X' AND field2 != 'Y' AND field3 = 'Z'" 

In Elasticsearch I'm starting from this:

{     "query": {         "filtered": {             "query": {                 "query_string": {                     "query": "*"                 }             },             "filter": {                 "term" : {                     "field1" : "286"                 }             }         }     } } 
like image 347
Pennywise83 Avatar asked Sep 09 '13 09:09

Pennywise83


People also ask

How do I search multiple fields in Elasticsearch?

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.

What is multi match query?

The multi_match query builds on the match query to allow multi-field queries: GET /_search { "query": { "multi_match" : { "query": "this is a test", "fields": [ "subject", "message" ] } } } The query string. The fields to be queried.

Is Elasticsearch good for full text search?

After indexing, you can search, sort, and filter complete documents—not rows of columnar data. This is a fundamentally different way of thinking about data and is one of the reasons ElasticSearch can perform a complex full-text search.


1 Answers

The sql query is equivalent to:

{   "query": {     "bool": {       "must": [         {           "term": {             "field1": "X"           }         },         {           "term": {             "field3": "Z"           }         }       ],       "must_not": {         "term": {           "field2": "Y"         }       }     }   } } 

In any case I recommend you to read a bit the doc before starting with elasticsearch if you are new.

There are lots of types of queries and some of them depends on how you index your data, for example for strings, you can analyze strings (lowercase, stem words, remove stopwords, ...) at index time. The query I posted will never match a doc whose field1 is "X" if you analyze that field at index time and convert it to lower case.

Once you know a little bit better elasticsearch you can use filters for improving your queries.

like image 85
moliware Avatar answered Sep 20 '22 07:09

moliware