我在 AWS 上使用 elasticsearch 来存储来自 Cloudfront 的日志。我创建了一个简单的查询,它将提供过去 24 小时内的所有条目,从新到旧排序:
{
"from": 0,
"size": 1000,
"query": {
"bool": {
"must": [
{ "match": { "site_name": "some-site" } }
],
"filter": [
{
"range": {
"timestamp": {
"lt": "now",
"gte": "now-1d"
}
}
}
]
}
},
"sort": [
{ "timestamp": { "order": "desc" } }
]
}
现在,我想排除某些来源(基于用户代理)的结果。所以我的问题归结为:
当某个字段包含某个字符串时,如何从结果中过滤掉条目?或者:
query.filter.where('cs_user_agent').does.not.contain('Some string')
(显然,这不是真正的代码。)
我试图理解 Elasticsearch 文档,但我找不到如何实现这一目标的好例子。
我希望这是有道理的。提前致谢!
好吧,我明白了。我所做的是将 Bool 查询与通配符结合使用:
{
"from": 0,
"size": 1000,
"query": {
"bool": {
"must": [
{ "match": { "site_name": "some-site" } }
],
"filter": [
{
"range": {
"timestamp": {
"lt": "now",
"gte": "now-1d"
}
}
}
],
"must_not": [
{ "wildcard": { "cs_user_agent": "some string*" } }
]
}
},
"sort": [
{ "timestamp": { "order": "desc" } }
]
}
这基本上匹配任何包含“some string”的用户代理字符串,然后将其过滤掉(因为“must_not”)。
我希望这可以帮助遇到此问题的其他人。
node.js 客户端版本:
const { from, size, value, tagsIdExclude } = req.body;
const { body } = await elasticWrapper.client.search({
index: ElasticIndexs.Tags,
body: {
from: from,
size: size,
query: {
bool: {
must: {
wildcard: {
name: {
value: `*${value}*`,
boost: 1.0,
rewrite: 'constant_score',
},
},
},
filter: {
bool: {
must_not: [
{
terms: {
id: tagsIdExclude ? tagsIdExclude : [],
},
},
],
},
},
},
},
},
});