Search code examples
elasticsearchamazon-elastic-beanstalkelastic-stack

Reverse Search in ElasticSearch Index


How can I reverse look up in elastic index to get result?

for e.g. I want to search email childabc@gmail.com elastic index which have keywords document {"item"} with data {"abc", "xyz", "amj"}

I want to serch "abc" of elastic data that is substring of email value childabc@gmail.com.

I already tried serching on google or for existing question, but didn't get more clarity with them.


Solution

  • You can use the ngram tokenizer for your use-case, you need to define you index setting and mapping as below:

    {
        "settings": {
            "index": {
                "analysis": {
                    "analyzer": {
                        "custom_analyzer": {
                            "filter": [
                                "lowercase"
                            ],
                            "tokenizer": "ngram",
                            "min_gram" : 2,
                            "max_gram" : 3
                        }
                    }
                },
                "max_ngram_diff" : 10
            }
        },
        "mappings": {
            "properties": {
                "item": {
                    "type": "text",
                    "analyzer": "custom_analyzer"
                }
            }
        }
    }
    

    And than index your documents

    {
        "item" : "abc"
    }
    
    {
        "item" : "xyz"
    }
    

    Now below search query returns your expected result

    {
        "query" : {
            "match" : {
                "item" : "childabc@gmail.com"
            }
        }
    }
    

    Search Result

     "hits": [
                {
                    "_index": "72961311",
                    "_type": "_doc",
                    "_id": "1",
                    "_score": 5.545177,
                    "_source": {
                        "item": "abc"
                    }
                }
            ]