Like search in Elasticsearch

Dixit Sourav picture Dixit Sourav · Jul 2, 2015 · Viewed 38.8k times · Source

I am using elasticsearch for filtering and searching from json file and I am newbie in this technology. So I am little bit confused how to write like query in elasticsearch.

select * from table_name where 'field_name' like 'a%'

This is mysql query. How do I write this query in Elasticsearch? I am using elasticsearch version 0.90.7.

Answer

I would highly suggest updating your ElasticSearch version if possible, there have been significant changes since 0.9.x.

This question is not quite specific enough, as there are many ways ElasticSearch can fulfill this functionality, and they differ slightly on your overall goal. If you are looking to replicate that SQL query exactly then in this case use the wildcard query or prefix query.

Using a wildcard query:

Note: Be careful with wildcard searches, they are slow. Avoid using wildcards at the beginning of your strings.

GET /my_index/table_name/_search
{
    "query": {
        "wildcard": {
            "field_name": "a*"
        }
    }
}

Or Prefix query

GET /my_index/table_name/_search
{
    "query": {
        "prefix": {
            "field_name": "a"
        }
    }
}

Or partial matching:

Note: Do NOT blindly use partial matching, while there are corner cases for it's use, correct use of analyzers is almost always better.

Also this exact query will be equivalent to LIKE '%a%', which again, could be better setup with correct use of mapping and a normal query search!

GET /my_index/table_name/_search
{
    "query": {
        "match_phrase": {
            "field_name": "a"
        }
    }
}

If you are reading this wondering about querying ES similarly for search-as-you-type I would suggest reading up on edge-ngrams, which relate to proper use of mapping depending on what you are attempting to do =)