分析仪是否会阻止字段突出显示?

时间:2015-04-01 06:41:56

标签: elasticsearch

你能帮我解决一下语言特定的分析器和弹性搜索的高度问题吗?

我需要通过查询字符串搜索文档并突出显示匹配的字符串。 这是我的映射:

{
    "usr": {
        "properties": {
            "text0": {
                "type": "string",
                "analyzer": "english"
            },
            "text1": {
                "type": "string"
            }
        }
    }
}

注意,对于“text0”字段,“english”分析器已设置,“text1”字段默认使用标准分析器。

在我的索引中,现在有一个文档:

hits": [{
    "_index": "tt",
    "_type": "usr",
    "_id": "AUxvIPAv84ayQMZV-3Ll",
    "_score": 1,
    "_source": {
        "text0": "highlighted. need to be highlighted.",
        "text1": "highlighted. need to be highlighted."
    }
}]

请考虑以下查询:

{
    "query": {
        "query_string" : {
            "query" : "highlighted"
        }
    },
    "highlight" : {
        "fields" : {
            "*" : {}
        }
    }
}

我希望文档中的每个字段都能突出显示,但突出显示只出现在“text1”字段中(其中没有设置分析器):

"hits": [{
    "_type": "usr", 
    "_source": {
        "text0": "highlighted. need to be highlighted.", 
        "text1": "highlighted. need to be highlighted."
    }, 
    "_score": 0.19178301, 
    "_index": "tt", 
    "highlight": {
        "text1": [
            "<em>highlighted</em>. need to be <em>highlighted</em>."
        ]
    }, 
    "_id": "AUxvIPAv84ayQMZV-3Ll"
}]

让我们考虑以下查询(由于分析器,我期望“突出显示”匹配“突出显示”):

{
    "query": {
        "query_string" : {
                "query" : "highlight"
            }
        },
    "highlight" : {
             "fields" : {
                 "*" : {}
             }
        }
}

但是根本没有响应:(英语分析仪在这里工作了吗?)

"hits": {
    "hits": [], 
    "total": 0, 
    "max_score": null
}

最后,考虑一些curl命令(请求和响应):

curl "http://localhost:9200/tt/_analyze?field=text0" -d "highlighted"

{"tokens":[{ 
    "token":"highlight",
    "start_offset":0,
    "end_offset":11,
    "type":"<ALPHANUM>",
    "position":1
}]}

curl "http://localhost:9200/tt/_analyze?field=text1" -d "highlighted" 

{"tokens":[{
    "token":"highlighted",
    "start_offset":0,
    "end_offset":11,
    "type":"<ALPHANUM>",
    "position":1
}]}

我们看到,通过英文和标准分析仪传递文本,结果是不同的。 最后,问题是:分析器是否会阻止字段突出显示?如何在全文搜索时突出显示我的字段?

P.S。我在使用Windows 8.1的本地计算机上使用elasticsearch v1.4.4。

1 个答案:

答案 0 :(得分:3)

它与您的查询有关。您正在使用query_string查询,而您没有指定该字段,因此默认情况下它会在_all字段中进行搜索。 这就是为什么你会看到奇怪的结果。将您的查询更改为multi_match查询,该查询会在两个字段中进行搜索:

{
    "query": {
        "multi_match": {
            "fields": [
                "text1",
                "text0"
            ],
            "query": "highlighted"
        }
    },
    "highlight": {
        "fields": {
            "*": {}
        }
    }
} 

现在突出显示两个字段的结果将在响应中返回。