Search ElasticSearch field contained in a value

后端 未结 1 408
故里飘歌
故里飘歌 2021-01-05 22:53

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

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

Meaning I\'m trying to fi

相关标签:
1条回答
  • 2021-01-05 23:02

    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

    0 讨论(0)
提交回复
热议问题