问题描述
我在 Elastic search 1.4 短语查询中遇到问题。我正在使用数据创建以下索引。
curl -XPUT 本地主机:9200/test
curl -XPOST localhost:9200/test/doc/1 -d '{"field1" : "abc-xyz"}'
curl -XPOST localhost:9200/test/doc/2 -d '{"field1" : "bcd-gyz"}'
因此默认情况下,field1 由弹性搜索和默认分析器进行分析。
{
"query": {
"filtered": {
"filter": {
"bool": {
"should": [
{
"query": {
"multi_match": {
"query": "abc\\-xyz OR bcd\\-gyz","type": "phrase","fields": [
"field1"
]
}
}
}
]
}
}
}
}
}
因此弹性搜索短语查询不适用于 OR 运算符。知道为什么它不起作用吗,这是因为文本中的特殊字符连字符 (-) 导致弹性搜索的限制吗?
解决方法
根据评论,添加使用 query string 的答案,该答案与 OR
一起使用在具有多个搜索的短语中,它不适用于多个多重匹配,因此必须使用 query string
.
使用在上一个答案中添加的相同索引文档,但使用以下搜索查询。
{
"query": {
"bool": {
"must": [
{
"query_string": {
"query": "\"abc-xyz\" OR \"bcd-gyz\"","fields": [
"title"
]
}
}
]
}
}
}
搜索结果
"hits": [
{
"_index": "phrasemulti","_type": "doc","_id": "1","_score": 0.05626005,"_source": {
"title": "bcd-gyz"
}
},{
"_index": "phrasemulti","_id": "2","_source": {
"title": "abc-xyz"
}
}
]
当您删除少量字符时,pharse
查询将不起作用,或者当您将运算符更改为 AND
时,示例数据不会返回预期的搜索结果。
{
"query": {
"bool": {
"must": [
{
"query_string": {
"query": "\"abc-xyz\" OR \"bcd-gz\"","fields": [
"title"
]
}
}
]
}
}
}
仅返回一个搜索结果,因为示例数据中不存在短语 bcd-gz
。
"hits": [
{
"_index": "phrasemulti","_source": {
"title": "abc-xyz"
}
}
]
,
下面的查询对我来说很好
{
"query": {
"filtered": {
"filter": {
"bool": {
"should": [
{
"query": {
"multi_match": {
"query": "abc-xyz",// note passing only one query without escaping hyphen
"type": "phrase","fields": [
"title"
]
}
}
}
]
}
}
}
}
}
带有解释参数的搜索结果
"hits": [
{
"_shard": 3,"_node": "1h3iipehS2abfclj51Vtsg","_index": "phrasemulti","_score": 1.0,"_source": {
"title": "abc-xyz"
},"_explanation": {
"value": 1.0,"description": "ConstantScore(BooleanFilter(QueryWrapperFilter(title:\"abc xyz\"))),product of:","details": [
{
"value": 1.0,"description": "boost"
},{
"value": 1.0,"description": "queryNorm"
}
]
}
}
]
根据短语验证其返回结果,因为查询 abc-xy
不返回任何结果。