There are many ways one can do full text search in ElasticSearch version 7.4. The complete list is below.

Full text queries

  • Intervals
  • Match
  • Match boolean prefix
  • Match phrase
  • Match phrase prefix
  • Multi-match
  • Common Terms Query
  • Query string
  • Simple query string

Query string and Simple query string are pretty close. SImple Query String is syntactically more loose than Query String, If you have error in your search command, Query String will fail whereas Simple Query String will not.


Today we will be discussing about Query String, although everything holds true for Simple Query String too.

Query String (query_string) has following syntax...

GET /_search
{
  "query": {
    "query_string" : {
      "query" : query
    }
  }
}

Above will search the query in all the fields.

Let us say we want to search iphone text in our elasticsearch db. Here is the complete query to do that...

http://localhost:9200/index/type/_search?pretty=True', '-d', '
{"query":{
  "query_string" :{
    "query":"iphone"
   }
  }
}
'

The good thing query_string is that query doesn't need to be exact. If you have multiple words, the order of words does't matter. For example let us look at following query...

http://localhost:9200/index/type/_search?pretty=True', '-d', '
{"query":{
  "query_string" :{
    "query":"battery laptop"
   }
  }
}
'

The first result i got is having following text.

"desc" : "Universal External Laptop Battery Power Packs

Also I see following...

"desc": "Laptop Batteries For 10,000+ Laptop Models"

query_string by default matches the text based on synonyms.

We can also enable fuzzy search by using regular expression in the query itself. Let say we want to search for virus and the only text we have in our db is antivirus. Then this query will not work...

http://localhost:9200/index/type/_search?pretty=True', '-d', '
{"query":{
  "query_string" :{
    "query":"virus"
   }
  }
}
'

To make it work we need to enable fuzzy logic by this...

http://localhost:9200/index/type/_search?pretty=True', '-d', '
{"query":{
  "query_string" :{
    "query":"*virus"
   }
  }
}
'

This is what I got as the output...

"desc" : "Get System Shield AntiVirus & AntiSpyware for $19.95"