搜索值中包含的ElasticSearch字段

Guy*_*and 5 full-text-search substring elasticsearch

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

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

意思是我试图找到所有文件,在这种情况下,产品名称是'milk'的子字符串.

我该怎么做?

Val*_*Val 5

我会选择利用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"
                }
            }
        }
    }
}'
Run Code Online (Sandbox Code Playgroud)

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

curl -XPOST 'localhost:9200/tests/test/_bulk' -d '
{"index":{}}
{"product_name": "bc"}
{"index":{}}
{"product_name": "cd"}
{"index":{}}
{"product_name": "def"}
'
Run Code Online (Sandbox Code Playgroud)

最后你可以像这样搜索:

curl -XPOST 'localhost:9200/tests/_search' -d '{
    "query": {
        "match": {
            "product_name": "abcde"
        }
    }
}'
Run Code Online (Sandbox Code Playgroud)

你会得到前两个文件bccd