1、批量查詢的好處
就是一條一條的查詢,比如說要查詢100條數據,那么就要發送100次網絡請求,這個開銷還是很大的
如果進行批量查詢的話,查詢100條數據,就只要發送1次網絡請求,網絡請求的性能開銷縮減100倍
mget的語法
mget批量查詢
GET /_mget
{
"docs" : [
{
"_index" : "test_index",
"_type" : "test_type",
"_id" : 1
},
{
"_index" : "test_index",
"_type" : "test_type",
"_id" : 2
}
]
}
{
"docs": [
{
"_index": "test_index",
"_type": "test_type",
"_id": "1",
"_version": 2,
"found": true,
"_source": {
"test_field1": "test field1",
"test_field2": "test field2"
}
},
{
"_index": "test_index",
"_type": "test_type",
"_id": "2",
"_version": 1,
"found": true,
"_source": {
"test_content": "my test"
}
}
]
}
(3)如果查詢的document是一個index下的不同type種的話
GET /test_index/_mget
{
"docs" : [
{
"_type" : "test_type",
"_id" : 1
},
{
"_type" : "test_type",
"_id" : 2
}
]
}
(4)如果查詢的數據都在同一個index下的同一個type下,最簡單了
GET /test_index/test_type/_mget
{
"ids": [1, 2]
}
3、mget的重要性
可以說mget是很重要的,一般來說,在進行查詢的時候,如果一次性要查詢多條數據的話,那么一定要用batch批量操作的api
盡可能減少網絡開銷次數,可能可以將性能提升數倍,甚至數十倍,非常非常之重要
bulk語法
POST /_bulk
{ "delete": { "_index": "test_index", "_type": "test_type", "_id": "3" }}
{ "create": { "_index": "test_index", "_type": "test_type", "_id": "12" }}
{ "test_field": "test12" }
{ "index": { "_index": "test_index", "_type": "test_type", "_id": "2" }}
{ "test_field": "replaced test2" }
{ "update": { "_index": "test_index", "_type": "test_type", "_id": "1", "_retry_on_conflict" : 3} }
{ "doc" : {"test_field2" : "bulk test1"} }
每一個操作要兩個json串,語法如下:
{"action": {"metadata"}}
{"data"}
舉例,比如你現在要創建一個文檔,放bulk里面,看起來會是這樣子的:
{"index": {"_index": "test_index", "_type", "test_type", "_id": "1"}}
{"test_field1": "test1", "test_field2": "test2"}
有哪些類型的操作可以執行呢?
(1)delete:刪除一個文檔,只要1個json串就可以了
{ "delete": { "_index": "test_index", "_type": "test_type", "_id": "3" }}
(2)create:PUT /index/type/id/_create,強制創建
{ "create": { "_index": "test_index", "_type": "test_type", "_id": "12" }}
{ "test_field": "test12" }
(3)index:普通的put操作,可以是創建文檔,也可以是全量替換文檔
{ "index": { "_index": "test_index", "_type": "test_type", "_id": "2" }}
{ "test_field": "replaced test2" }
(4)update:執行的partial update操作
{ "update": { "_index": "test_index", "_type": "test_type", "_id": "1", "_retry_on_conflict" : 3} }
{ "doc" : {"test_field2" : "bulk test1"} }
注意:
bulk操作中,任意一個操作失敗,是不會影響其他的操作的,但是在返回結果里,會告訴你異常日志。bulk request會加載到內存里,如果太大的話,性能反而會下降,因此需要反復嘗試一個最佳的bulk size。一般從1000~5000條數據開始,嘗試逐漸增加。另外,如果看大小的話,最好是在5~15MB之間。
multi-index和multi-type搜索模式
告訴你如何一次性搜索多個index和多個type下的數據
/_search:所有索引,所有type下的所有數據都搜索出來
/index1/_search:指定一個index,搜索其下所有type的數據
/index1,index2/_search:同時搜索兩個index下的數據
/test1_*,test2_*/_search:按照通配符去匹配多個索引
/index1/type1/_search:搜索一個index下指定的type的數據
/index1/type1,type2/_search:可以搜索一個index下多個type的數據
/index1,index2/type1,type2/_search:搜索多個index下的多個type的數據
/_all/type1,type2/_search:_all,可以代表搜索所有index下的指定type的數據
分頁搜索
將這9條數據分成3頁,每一頁是3條數據
GET /test_index/test_type/_search?from=0&size=3