搜索项目上线了,接下来又有新的应用场景,比如说很多文章都有品牌属性,品牌又有很多分类,比如addidas有鞋子、衣服,总结下来有两种需求:
具体说下第一种搜索需求:
1:使用 match 的 operator 完成两个词的并行分析
#content索引的分析器是hanlp
POST test/_doc/1
{
"content" : "鞋子 xx vans"
}
POST test/_doc/1
{
"content" : "vans xx 鞋子"
}
POST test/_doc/3
{
"content" : "我和她去哪儿"
}
#分为四个词:我、和、她、去哪儿
POST /_analyze
{
"text": "我和她去哪儿",
"analyzer": "hanlp"
}
POST test/_doc/4
{
"content" : "阿迪达斯鞋子"
}
进行分析,只要有vans和鞋子都能搜索到:
"must": [
{
"match": {
"content": {
"operator": "and",
"query": "vans 鞋子" # "query": "鞋子 vans"
}
}
}
]
下面这个能搜到到,“我和”(或者“我她”)会分为两个词,所以会最终匹配到:
"must": [
{
"match": {
"content": {
"operator": "and",
"query": "我和 去哪儿"
}
}
}
]
所以要仔细体会 and 背后的搜索过程,由于品牌的分词还是比较准确的,所以不会搜索到太多无关的信息。
2:跨字段搜索
要用到 and operator,如果对多个字段进行and搜索呢?只要不同字段中都and包含这些搜索语就可以。
可 most_fields 是不支持 and operator 操作符的,所以需要使用cross_fields:
"must": [
{
"multi_match": {
"query": "vans 鞋子",
"operator": "and",
"fields": [
"title",
"content"
],
"type": "cross_fields",
"tie_breaker": 0.3
}
}
],
"filter": [
{
"term": {
"brandid": "0"
}
}
]
3:尝试使用match_phrase解决and
match_phrase 也有一定的应用场景,也会分词,但满足不了本文的需求,根本的原因它需要保证索引搜索的顺序,进一步理解了它的本质。
4:匹配多个关键字
匹配有多个名称,可以根据多个名称搜索话题信息(也是一个索引),如果使用match非常简单,比如:
{
"query": {
"match": {
"title": {
"query": "爱笑 安利"
}
}
}
}
但match的分词太只能,会导致仅仅包含“笑”的话题也被搜索出来,所以使用match_phrase,结合minimum_should_match,所以用到现在mutch和match_phrase的理解非常重要。
{
"query": {
"bool": {
"should": [
{
"match_phrase": {
"title": {
"query": "爱笑"
}
}
},
{
"match_phrase": {
"title": {
"query": "安利"
}
}
},
{
"term": {
"type": {
"value": "1",
"boost": 2
}
}
}
],
"minimum_should_match": 1
}
}
}