在elasticsearch

时间:2015-07-03 06:17:49

标签: elasticsearch

如何在弹性搜索结果中包含不匹配的项目?

例如,

我的列表有点像这样:

[
    {
        "_index": "products",
        "_type": "71",
        "_id": "556637aed75a1334f69db5d7",
        "_score": 1,
        "_source": {
            "product_id": "556637aed75a1334f69db5d7",
            "categories": [
                28
            ],
            "tags": ["shirts"]
        }
    },
    {
        "_index": "products",
        "_type": "71",
        "_id": "556637aed75a1334f69db5d2",
        "_score": 1,
        "_source": {
            "product_id": "556637aed75a1334f69db5d2",
            "categories": [
                27
            ],
            "tags": []
        }
    },
    {
        "_index": "products",
        "_type": "71",
        "_id": "556637aed75a1334f69db5e4",
        "_score": 1,
        "_source": {
            "product_id": "556637aed75a1334f69db5e4",
            "categories": [
                26
            ],
            "tags": [
                "shoes"
            ]
        }
    },
    {
        "_index": "products",
        "_type": "71",
        "_id": "556637aed75a1334f69db5dd",
        "_score": 1,
        "_source": {
            "product_id": "556637aed75a1334f69db5dd",
            "categories": [
                23
            ],
            "tags": []
        }
    }
]

我希望得到一个结果,首先显示匹配的文档,然后显示不匹配的文档。

如果我的查询看起来像这样:

{
    "query": {
        "terms": {
            "tags": [
                "shorts",
                "shoes"
            ]
        }
    },
    "sort": [ "_score" ]
}

我会只列出包含shoesshorts标记的项目。

我想在匹配的项目之后显示不匹配的项目。

另外,我想在搜索查询中添加categories。有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:1)

首先,您sort上不需要_score。默认情况下,结果的排序是在分数上完成的。

其次,没有显示“无与伦比”的文档。您需要定义自己的匹配“不匹配”的规则。在我看来,您需要一个match_all

第三,我建议使用bool,其中您拥有的每个条件(匹配标记,匹配类别,match_all - 以匹配“不匹配的”文档)应放在{{1}中}}。每个条件都会为分数增加一些东西。这意味着,条件匹配越多,得分越高。如果shouldtags不匹配,则剩余文档的分数(匹配categories的分数)将会很低,因此它们将位于列表的末尾。

match_all
相关问题