我需要创建 Elasticsearch 查询以从已索引到 Elasticsearch 索引的日志中过滤掉。
问题陈述是列出电子邮件为“[email protected]”的用户的日志。 '并且是company_id'123'的一部分。随着添加更多过滤器,日志列表也会发生变化。例如,具有事件 checkin 或 checkout 的日志或温度范围在 28.7 - 37.8 之间的用户。
等效的 mysql 查询是:
select * from logs
where
(
company_id = 123 or company_id is null // company_id may be missing
)
AND
(
email = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="295d4c5a5d6950465944484045074a4644" rel="noreferrer noopener nofollow">[email protected]</a>'
)
AND
(
event = 'checkIn'
or event = 'checkOut'
or
(
event = 'temperature'
AND temperature >= 28.7
AND temperature <= 37.8
)
)
其中,logs 是索引名称,company_id、email、event、温度、create_date 是字段(列)名称。
我生成的查询是:
'query' => {
'bool' => {
'must' => [
{
'bool' => {
'must' => {
'match' => {
"email.keyword" => {
'query' => $email, 'fuzziness' => 'auto'
}
}
},
'should' => {
{
'match' => {
"event" => {
'query' => "checkIn"
}
}
},
{
'match' => {
"event" => {
'query' => "checkOut"
}
}
},
{
'range' => {
"temperature" => {
"gte" => 28.7,
"lte" => 37.8
}
}
}
}
}
{
],
'should' => [
{
'bool' => {
'should' => [
{
'match' => {
"company_id" => [
'query' => $company_id
]
}
}
],
'must_not' => [
{
'exists' => {
'field' => 'company_id'
}
}
]
}
}
]
}
}
但这并没有达到应有的效果。
如有任何帮助,我们将不胜感激。 谢谢
最佳答案
与您的 SQL 查询相对应的 DSL 查询如下。它与您拥有的略有不同。
{
"query": {
"bool": {
"filter": [
{
"bool": {
"minimum_should_match": 1,
"should": [
{
"term": {
"company_id": "123"
}
},
{
"bool": {
"must_not": {
"exists": {
"field": "company_id"
}
}
}
}
]
}
},
{
"term": {
"email.keyword": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1460716760546d7b6479757d783a777b79" rel="noreferrer noopener nofollow">[email protected]</a>"
}
},
{
"bool": {
"minimum_should_match": 1,
"should": [
{
"terms": {
"event": ["checkIn", "checkOut"]
}
},
{
"bool": {
"filter": [
{
"term": {
"event": "temperature"
}
},
{
"range": {
"temperature": {
"gte": 28.7,
"lte": 37.8
}
}
}
]
}
}
]
}
}
]
}
}
}
关于elasticsearch - 使用 Elasticsearch 进行过滤查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66331236/