Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search ElasticSearch field contained in a value

I'm trying to run similar field query in ElasticSearch:

select * from products where 'milk' like '%'+name+'%'

Meaning I'm trying to find all the documents that the product name in this case is a sub string of 'milk'.

How can I do it?

like image 378
Guy Korland Avatar asked May 25 '16 16:05

Guy Korland


People also ask

How do I search a specific field in Elasticsearch?

There are two recommended methods to retrieve selected fields from a search query: Use the fields option to extract the values of fields present in the index mapping. Use the _source option if you need to access the original data that was passed at index time.

Does Elasticsearch have schema?

The schema in Elasticsearch is a mapping that describes the the fields in the JSON documents along with their data type, as well as how they should be indexed in the Lucene indexes that lie under the hood. Because of this, in Elasticsearch terms, we usually call this schema a “mapping”.

How do I query keyword in Elasticsearch?

Querying Elasticsearch works by matching the queried terms with the terms in the Inverted Index, the terms queried and the one in the Inverted Index must be exactly the same, else it won't get matched.

How do I browse Elasticsearch data?

You can use the search API to search and aggregate data stored in Elasticsearch data streams or indices. The API's query request body parameter accepts queries written in Query DSL. The following request searches my-index-000001 using a match query. This query matches documents with a user.id value of kimchy .


1 Answers

I would go with a custom analyzer leveraging ngrams. First create an index like this:

curl -XPUT 'localhost:9200/tests' -d '
{
    "settings" : {
        "analysis" : {
            "analyzer" : {
                "my_analyzer" : {
                    "tokenizer" : "ngrams"
                }
            },
            "tokenizer" : {
                "ngrams" : {
                    "type" : "nGram",
                    "min_gram" : "2",
                    "max_gram" : "10"
                }
            }
        }
    },
    "mappings": {
        "test": {
            "properties": {
                "product_name": {
                    "type": "string",
                    "analyzer": "standard",
                    "search_analyzer": "my_analyzer"
                }
            }
        }
    }
}'

Then you can index some data:

curl -XPOST 'localhost:9200/tests/test/_bulk' -d '
{"index":{}}
{"product_name": "bc"}
{"index":{}}
{"product_name": "cd"}
{"index":{}}
{"product_name": "def"}
'

And finally you can search like this:

curl -XPOST 'localhost:9200/tests/_search' -d '{
    "query": {
        "match": {
            "product_name": "abcde"
        }
    }
}'

And you'll get the first two documents bc and cd

like image 168
Val Avatar answered Sep 26 '22 05:09

Val