簡體   English   中英

在同一查詢中使用And&or進行Elasticsearch查詢-布爾查詢?

[英]Elasticsearch Query with And & Or in the Same Query - Bool Query?

我正在使用彈性2.2和Sense。

我有以下問題來澄清我的思考方式。

Elasticsearch是全文搜索引擎,而不是SQL數據庫,但是在ES查詢中仍然可以考慮代數(AND,OR,WHERE等)。

我不在乎這方面的分數。

假設我有以下平面文檔類型客戶,其中所有字段均為not_analysed ,則映射中的屬性為:

"properties": {
          "address": {
            "type": "string",
            "index": "not_analyzed"
          },
          "age": {
            "type": "long"
          },
          "customerid": {
            "type": "string",
            "index": "not_analyzed"
          },
          "firstname": {
            "type": "string",
            "index": "not_analyzed"
          },
          "lastname": {
            "type": "string",
            "index": "not_analyzed"
          },
          "updated": {
            "type": "date",
            "format": "date_hour_minute_second_millis"
          }
        }

現在,我索引:

PUT customers_ds/customers/1
{
  "customerid": "1",
  "firstname": "Marie",
  "address": "Brazil",
  "updated": "2017-01-13T02:36:37.292",
  "lastname": "Doe",
  "age": 20 
}



PUT customers_ds/customers/2
{
  "customerid": "1",
  "firstname": "John",
  "address": "North America",
  "updated": "2017-01-13T02:36:37.292",
  "lastname": "Doe",
  "age": 25 
}

我應該寫什么查詢說:

我希望所有姓瑪麗的客戶或居住在“北美”的客戶

select * from customers where firstname = "Marie" or address = "North America"

如何編寫這樣的ES查詢?

最后,如何編寫:

select * from customers where firstname = "Marie" and lastname = "Doe" or address = "North America"

在最后一個查詢中,我想從ES中獲取回來:

瑪麗和約翰,因為OR。 或地址=“ North America”,而Mary將在AND中進行匹配。 讓我知道是否清楚。

???

如果要進行OR查詢,可以這樣進行:

{
   "query": {
      "bool": {
         "minimum_should_match": 1,
         "should": [
            {
               "term": {
                  "firstname": "Marie"
               }
            },
            {
               "term": {
                  "address": "North America"
               }
            }
         ]
      }
   }
}

如果您要使用AND查詢,則可以簡單地filter替換“ should (如果您在意分數,則must替換”):

{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "firstname": "Marie"
                }
              },
              {
                "term": {
                  "lastname": "Doe"
                }
              }
            ]
          }
        },
        {
          "term": {
            "address": "North America"
          }
        }
      ]
    }
  }
}

對於OR查詢,請使用過濾器,我們不會為您打分

{
    "filtered" : {
        "query" : {
            "term" : { "firstname" : "Marie" }
        },
        "filter" : {
            "or" : [
                {
                    "term" : { "address" : "north america" }
                }
            ]
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM