Multi Get API
Multi Get API允許基於索引、類型(可選)和id(可能還有路由)獲得多個文檔,響應包括一個docs
數組,其中包含所有獲取的文檔,以便與原始的multi-get請求相對應(如果特定get失敗,則在響應中包括包含此錯誤的對象),成功get的結構在結構上類似於get API提供的文檔。
這裏有一個例子:
GET /_mget
{
"docs" : [
{
"_index" : "test",
"_type" : "_doc",
"_id" : "1"
},
{
"_index" : "test",
"_type" : "_doc",
"_id" : "2"
}
]
}
mget
端點還可以用於索引(在這種情況下,body中不需要索引):
GET /test/_mget
{
"docs" : [
{
"_type" : "_doc",
"_id" : "1"
},
{
"_type" : "_doc",
"_id" : "2"
}
]
}
和類型:
GET /test/_doc/_mget
{
"docs" : [
{
"_id" : "1"
},
{
"_id" : "2"
}
]
}
在這種情況下,可以直接使用ids
元素來簡化請求:
GET /test/_doc/_mget
{
"ids" : ["1", "2"]
}
源過濾
默認情況下,每個文檔將返回_source
字段(如果存儲了的話),與get API類似,通過使用_source
參數,你可以只檢索_source
的一部分(或者完全沒有),你還可以使用url參數_source
、_source_include
和_source_exclude
來指定默認值,當沒有針對每個文檔指令時將使用默認值。
例如:
GET /_mget
{
"docs" : [
{
"_index" : "test",
"_type" : "_doc",
"_id" : "1",
"_source" : false
},
{
"_index" : "test",
"_type" : "_doc",
"_id" : "2",
"_source" : ["field3", "field4"]
},
{
"_index" : "test",
"_type" : "_doc",
"_id" : "3",
"_source" : {
"include": ["user"],
"exclude": ["user.location"]
}
}
]
}
字段
可以指定特定的存儲字段,以便對每個要獲取的文檔進行檢索,類似於get API的stored_fields
參數,例如:
GET /_mget
{
"docs" : [
{
"_index" : "test",
"_type" : "_doc",
"_id" : "1",
"stored_fields" : ["field1", "field2"]
},
{
"_index" : "test",
"_type" : "_doc",
"_id" : "2",
"stored_fields" : ["field3", "field4"]
}
]
}
或者,你可以將查詢字符串中的stored_fields
參數指定爲應用於所有文檔的默認參數。
GET /test/_doc/_mget?stored_fields=field1,field2
{
"docs" : [
{
"_id" : "1"
},
{
"_id" : "2",
"stored_fields" : ["field3", "field4"]
}
]
}
-
"_id" : "1"
=> 返回field1
、field2
。 -
"stored_fields" : ["field3", "field4"]
=> 返回field3
、field4
。
路由
還可以將路由值指定爲參數:
GET /_mget?routing=key1
{
"docs" : [
{
"_index" : "test",
"_type" : "_doc",
"_id" : "1",
"routing" : "key2"
},
{
"_index" : "test",
"_type" : "_doc",
"_id" : "2"
}
]
}
在本例中,文檔test/_doc/2
將從與路由鍵key1
對應的碎片中獲取,但是,文檔test/_doc/1
將從與路由鍵key2
對應的碎片中獲取。