Elasticsearch - 不需要完全匹配
Elasticsearch - Not require an exact match
目前我的 elasticsearch 索引中有一个项目,标题为:testing123
。
当我搜索它时,如果我完全搜索testing123
,我只能返回它。但是,我希望能够搜索 testing
并将其返回。
我怎样才能让搜索必须以该字词开头但又不是完全匹配?
我相信您正在寻找 wildcards。
Matches documents that have fields matching a wildcard expression. Supported wildcards are *, which matches any character sequence (including the empty one), and ?, which matches any single character.
通配符基本上是“匹配此处的任何内容”。所以你的搜索看起来像
testing*
哪个会匹配
testing
testing123
testingthings
但不匹配
test123ing
或
test
在映射中使用 Simple Analyzer。
使用标准(默认)和简单分析器为 title
字段建立索引:
POST /demo
{
"mappings": {
"doc": {
"properties": {
"title": {
"type": "string",
"fields": {
"simple": {
"type": "string",
"analyzer": "simple"
}
}
}
}
}
}
}
索引文档
POST /demo/doc/1
{
"title": "testing123"
}
最后,使用 multi_match
查询进行搜索:
POST /demo/doc/_search
{
"query": {
"multi_match": {
"fields": [
"title",
"title.simple"
],
"query": "testing"
}
}
}
此查询returns文档。如果您要将查询词更改为 testing123
,那么也会有一个匹配项。
另一种可能的解决方案是使用 Prefix Query。
目前我的 elasticsearch 索引中有一个项目,标题为:testing123
。
当我搜索它时,如果我完全搜索testing123
,我只能返回它。但是,我希望能够搜索 testing
并将其返回。
我怎样才能让搜索必须以该字词开头但又不是完全匹配?
我相信您正在寻找 wildcards。
Matches documents that have fields matching a wildcard expression. Supported wildcards are *, which matches any character sequence (including the empty one), and ?, which matches any single character.
通配符基本上是“匹配此处的任何内容”。所以你的搜索看起来像
testing*
哪个会匹配
testing
testing123
testingthings
但不匹配
test123ing
或
test
在映射中使用 Simple Analyzer。
使用标准(默认)和简单分析器为 title
字段建立索引:
POST /demo
{
"mappings": {
"doc": {
"properties": {
"title": {
"type": "string",
"fields": {
"simple": {
"type": "string",
"analyzer": "simple"
}
}
}
}
}
}
}
索引文档
POST /demo/doc/1
{
"title": "testing123"
}
最后,使用 multi_match
查询进行搜索:
POST /demo/doc/_search
{
"query": {
"multi_match": {
"fields": [
"title",
"title.simple"
],
"query": "testing"
}
}
}
此查询returns文档。如果您要将查询词更改为 testing123
,那么也会有一个匹配项。
另一种可能的解决方案是使用 Prefix Query。