elasticsearch - 如何在 Elasticsearch 中匹配前缀

标签 elasticsearch

假设在我的 elasticsearch 索引中有一个名为“dots”的字段,它将包含一串标点符号分隔的单词(例如“first.second.third”)。

我需要搜索例如“first.second”,然后获取其“dots”字段包含恰好为“first.second”或以“first.second.”开头的字符串的所有条目。

我在理解文本查询的工作原理时遇到了问题,至少我无法创建完成这项工作的查询。

最佳答案

Elasticsearch 有 Path Hierarchy Tokenizer正是为这种用例创建的。以下是如何为您的索引设置它的示例:

# Create a new index with custom path_hierarchy analyzer 
# See http://www.elasticsearch.org/guide/reference/index-modules/analysis/pathhierarchy-tokenizer.html
curl -XPUT "localhost:9200/prefix-test" -d '{
    "settings": {
        "analysis": {
            "analyzer": {
                "prefix-test-analyzer": {
                    "type": "custom",
                    "tokenizer": "prefix-test-tokenizer"
                }
            },
            "tokenizer": {
                "prefix-test-tokenizer": {
                    "type": "path_hierarchy",
                    "delimiter": "."
                }
            }
        }
    },
    "mappings": {
        "doc": {
            "properties": {
                "dots": {
                    "type": "string",
                    "analyzer": "prefix-test-analyzer",
                    //"index_analyzer": "prefix-test-analyzer", //deprecated
                    "search_analyzer": "keyword"
                }
            }
        }
    }
}'
echo
# Put some test data
curl -XPUT "localhost:9200/prefix-test/doc/1" -d '{"dots": "first.second.third"}'
curl -XPUT "localhost:9200/prefix-test/doc/2" -d '{"dots": "first.second.foo-bar"}'
curl -XPUT "localhost:9200/prefix-test/doc/3" -d '{"dots": "first.baz.something"}'
curl -XPOST "localhost:9200/prefix-test/_refresh"
echo
# Test searches. 
curl -XPOST "localhost:9200/prefix-test/doc/_search?pretty=true" -d '{
    "query": {
        "term": {
            "dots": "first"
        }
    }
}'
echo
curl -XPOST "localhost:9200/prefix-test/doc/_search?pretty=true" -d '{
    "query": {
        "term": {
            "dots": "first.second"
        }
    }
}'
echo
curl -XPOST "localhost:9200/prefix-test/doc/_search?pretty=true" -d '{
    "query": {
        "term": {
            "dots": "first.second.foo-bar"
        }
    }
}'
echo
curl -XPOST "localhost:9200/prefix-test/doc/_search?pretty=true&q=dots:first.second"
echo

关于elasticsearch - 如何在 Elasticsearch 中匹配前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12117275/

相关文章:

docker - 在 docker 中安装 Elasticsearch

elasticsearch - 使用Must Field值编写Elasticsearch Nest Bool查询

postgresql - Elasticsearch使用Node.js添加数据

elasticsearch - 如何在Elastic APM中删除服务?

c# - 如何使用 Serilog 在 Json 中获取日志级别 - .NET Core 3.1

python - 在elasticsearch中存储 token 频率,而不是存储文本

json - 在couchdb中使用elasticsearch索引json中的名称

php - PHP中的Elasticsearch映射类型

java - ElasticSearch SpringBoot+Spring Data : java. lang.IllegalStateException:在接口(interface)上找不到合适的构造函数

docker - 通过setup.yml将保存的对象导入Kibana