我有一个ElasticSearch函数,可以匹配两个条件。但是现在“type”是可选的,如果没有设置type,我希望返回所有cookie,如果设置了type,我希望得到与下面查询相同的结果。Type是一个枚举(如果这很重要的话)。
export const searchCookies: HttpFunction = enrichCloudFunction(async (req, res) => {
const {
query: { type, cookies, from, size },
} = validateCookieQuery(req)
const {
hits: { hits },
} = await elastic.search<ExtendedStuff>({
from: from || 0,
index: cookieIndex({ prefix: config.prefix }),
query: {
bool: {
must: [
{
match: { 'cookie.id': cookie },
},
{
match: { type },
},
],
},
},
size: size || 20,
})
res.json(hits.map((x) => x._source))
})
这可能是一个超级琐碎的事情,但这是我第一次使用ElasticSearch,我是超级困惑。
2条答案
按热度按时间c2e8gylq1#
我会查看Elastic文档中的可用选项,但您也可以按照以下方式提出一个条件语句:
2uluyalo2#
您可以使用should clause,如果满足任何子句,它将返回一个文档。
1.不能存在-这将返回没有字段集的文档
此外,您可以使用must/filter -返回具有匹配cookie id且满足任何should子句文档。
如果您只是在筛选,请使用筛选器。2筛选器不计算分数,因此速度更快。