帶有示例的基本搜尋引數
預設情況下,完整索引文件作為所有搜尋的一部分返回。這被稱為源(搜尋命中中的 _source 欄位)。如果我們不希望返回整個源文件,我們只能請求返回源中的幾個欄位,或者我們可以將 _source 設定為 false 以完全省略該欄位。
此示例顯示如何從搜尋中返回兩個欄位 account_number 和 balance(在 _source 內):
curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
{
"query": { "match_all": {} },
"_source": ["account_number", "balance"]
}'
請注意,上面的示例只是簡化了 _source 欄位中返回的資訊。它仍將只返回一個名為 _source 的欄位,但只包含欄位 account_number 和 balance。
如果你來自 SQL 背景,則上述內容在概念上與 SQL 查詢有些相似
SELECT account_number, balance FROM bank;
現在讓我們轉到查詢部分。以前,我們已經看到 match_all 查詢如何用於匹配所有文件。現在讓我們介紹一個稱為匹配查詢的新查詢,它可以被認為是一個基本的現場搜尋查詢(即針對特定欄位或欄位集進行的搜尋)。
此示例返回 account_number 設定為 20 的帳戶:
curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
{
"query": { "match": { "account_number": 20 } }
}'
此示例返回 address 中包含術語 mill 的所有帳戶:
curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
{
"query": { "match": { "address": "mill" } }
}'
此示例返回 address 中包含術語 mill 或 lane 的所有帳戶:
curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
{
"query": { "match": { "address": "mill lane" } }
}'
此示例是 match(match_phrase)的變體,它將查詢拆分為術語,僅返回包含 address 中相對於彼此相同位置的所有項的文件 [1] 。
curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
{
"query": { "match_phrase": { "address": "mill lane" } }
}'
我們現在介紹 bool(ean) 查詢。bool 查詢允許我們使用布林邏輯將較小的查詢組成更大的查詢。
此示例組成兩個匹配查詢,並返回地址中包含 mill 和 lane 的所有帳戶:
curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
{
"query": {
"bool": {
"must": [
{ "match": { "address": "mill" } },
{ "match": { "address": "lane" } }
]
}
}
}'
在上面的示例中,bool must 子句指定必須為 true 才能將文件視為匹配的所有查詢。
相反,此示例組成兩個匹配查詢並返回 address 中包含 mill 或 lane 的所有帳戶:
curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
{
"query": {
"bool": {
"should": [
{ "match": { "address": "mill" } },
{ "match": { "address": "lane" } }
]
}
}
}'
在上面的示例中,bool should 子句指定了一個查詢列表,其中任何一個查詢必須為 true 才能將文件視為匹配項。
此示例組成兩個匹配查詢,並返回 address 中既不包含 mill 也不包含 lane 的所有帳戶:
curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
{
"query": {
"bool": {
"must_not": [
{ "match": { "address": "mill" } },
{ "match": { "address": "lane" } }
]
}
}
}'
在上面的示例中,bool must_not 子句指定了一個查詢列表,對於文件而言,這些查詢都不能為 true。
我們可以在 bool 查詢中同時組合 must,should 和 must_not 子句。此外,我們可以在任何這些 bool 子句中組合 bool 查詢來模仿任何複雜的多級布林邏輯。
此示例返回屬於 40 歲且不住在華盛頓(簡稱 WA)的人的所有帳戶:
curl -XPOST 'localhost:9200/bank/_search?pretty' -d '
{
"query": {
"bool": {
"must": [
{ "match": { "age": "40" } }
],
"must_not": [
{ "match": { "state": "WA" } }
]
}
}
}'