該API用于在Elasticsearch中搜索內(nèi)容。用戶可以通過(guò)發(fā)送帶有查詢字符串作為參數(shù)的get請(qǐng)求進(jìn)行搜索,或者可以在發(fā)布請(qǐng)求的消息正文中發(fā)布查詢。搜索 api 主要是多索引、多類型的。
Elasticsearch允許我們搜索所有索引或某些特定索引中存在的文檔。例如,如果我們需要搜索名稱包含“ central”的所有文檔,則可以執(zhí)行以下操作:
GET /_all/_search?q=city:paprola
在運(yùn)行上面的代碼時(shí),我們得到以下響應(yīng)-
{
"took" : 33,
"timed_out" : false,
"_shards" : {
"total" : 7,
"successful" : 7,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.9808292,
"hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "5",
"_score" : 0.9808292,
"_source" : {
"name" : "Central School",
"description" : "CBSE Affiliation",
"street" : "Nagan",
"city" : "paprola",
"state" : "HP",
"zip" : "176115",
"location" : [
31.8955385,
76.8380405
],
"fees" : 2200,
"tags" : [
"Senior Secondary",
"beautiful campus"
],
"rating" : "3.3"
}
}
]
}
}可以使用統(tǒng)一資源標(biāo)識(shí)符在搜索操作中傳遞許多參數(shù)-
| 序號(hào) | 參數(shù)及說(shuō)明 |
|---|---|
| 1 | Q 此參數(shù)用于指定查詢字符串 |
| 2 | lenient 此參數(shù)用于指定查詢字符串。只要將此參數(shù)設(shè)置為 true,就可以忽略基于 Formatbased 的錯(cuò)誤。默認(rèn)情況下它是假的。 |
| 3 | fields 此參數(shù)用于指定查詢字符串 |
| 4 | sort 我們可以通過(guò)使用這個(gè)參數(shù)得到排序的結(jié)果,這個(gè)參數(shù)的可能值是fieldName, fieldName:asc/ fieldName:desc |
| 5 | timeout 我們可以通過(guò)使用這個(gè)參數(shù)來(lái)限制搜索時(shí)間,并且響應(yīng)只包含指定時(shí)間內(nèi)的命中。默認(rèn)情況下,沒(méi)有超時(shí) |
| 6 | terminate_after 們可以將響應(yīng)限制為每個(gè)碎片的指定數(shù)量的文檔,到達(dá)該分片時(shí),查詢將提前終止。默認(rèn)情況下,沒(méi)有 termin_after. |
| 7 | from 要返回的命中數(shù)的起始索引。默認(rèn)為0。 |
| 8 | size 它表示要返回的命中數(shù),默認(rèn)值為10。 |
我們還可以在請(qǐng)求正文中使用查詢DSL來(lái)指定查詢,并且在前面的章節(jié)中已經(jīng)給出了很多示例。這里給出一個(gè)這樣的實(shí)例-
POST /schools/_search
{
"query":{
"query_string":{
"query":"up"
}
}
}在運(yùn)行上面的代碼時(shí),我們得到以下響應(yīng)-
{
"took" : 11,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 0.47000363,
"hits" : [
{
"_index" : "schools",
"_type" : "school",
"_id" : "4",
"_score" : 0.47000363,
"_source" : {
"name" : "City Best School",
"description" : "ICSE",
"street" : "West End",
"city" : "Meerut",
"state" : "UP",
"zip" : "250002",
"location" : [
28.9926174,
77.692485
],
"fees" : 3500,
"tags" : [
"fully computerized"
],
"rating" : "4.5"
}
}
]
}
}