搜索一个值中包含的 ElasticSearch 字段

Search ElasticSearch field contained in a value

我正在尝试 运行 在 ElasticSearch 中查询类似的字段:

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

意思是我正在尝试查找本例中的产品名称是 'milk'.

的子字符串的所有文档

我该怎么做?

我会使用利用 ngrams 的自定义分析器。首先像这样创建一个索引:

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"
                }
            }
        }
    }
}'

然后你可以索引一些数据:

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

最后你可以这样搜索:

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

您将获得前两个文档 bccd