mget(可以通過索引、型別、或ID一次得到同一索引或不同索引庫裡的文件集合) & mapping
阿新 • • 發佈:2019-01-07
使用multi get API可以通過索引名、型別名、文件id一次得到一個文件集合,文件可以來自同一個索引庫,也可以來自不同索引庫。示例如下:
MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("twitter", "tweet", "1") //註釋1
.add("twitter", "tweet", "2", "3", "4") //註釋2
.add("another", "type" , "foo") //註釋3
.get();
for (MultiGetItemResponse itemResponse : multiGetItemResponses) { //註釋4
GetResponse response = itemResponse.getResponse();
if (response.isExists()) { //註釋5
String json = response.getSourceAsString(); //註釋6
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
註釋1: 通過單一的ID獲取一個文件.
註釋2:傳入多個id,從相同的索引名/型別名中獲取多個文件.
註釋3:可以同時獲取不同索引中的文件.
註釋4:遍歷結果集.
註釋5:檢驗文件是否存在.
註釋6:獲取文件源.
一、獲取索引的所有mapping
通過java客戶端獲取mapping:
package elasticsearch.in.action.client;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.elasticsearch .client.transport.TransportClient;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
public class TransClient {
public static String clusterName = "elasticsearch";// 叢集名稱
public static String serverIP = "127.0.0.1";// 伺服器IP
public static void main(String[] args) {
System.out.println(getMapping("news", "sportnews"));
}
public static String getMapping(String indexname, String typename) {
Settings settings = Settings.settingsBuilder().put("cluster.name", clusterName).build();
String mapping="";
try {
TransportClient client = TransportClient.builder().settings(settings).build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(serverIP), 9300));
ImmutableOpenMap<String, MappingMetaData> mappings = client.admin().cluster().prepareState().execute()
.actionGet().getState().getMetaData().getIndices().get(indexname).getMappings();
mapping = mappings.get(typename).source().toString();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return mapping;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
二、獲取所有的type以及每個type的mapping
mapping資訊都是ImmutableOpenMap
for (ObjectObjectCursor<String, MappingMetaData> cursor : mappings) {
System.out.println(cursor.key); // 索引下的每個type
System.out.println(cursor.value.getSourceAsMap()); // 每個type的mapping
}