使用multi get API可以通过索引名、类型名、文档id一次得到一个文档集合,文档可以来自同一个索引库,也可以来自不同索引库。示例如下:
MultiGetResponse multiGetItemResponses = client.prepareMultiGet()
.add("twitter", "tweet", "1")
.add("twitter", "tweet", "2", "3", "4")
.add("another", "type", "foo")
.get();
for (MultiGetItemResponse itemResponse : multiGetItemResponses) {
GetResponse response = itemResponse.getResponse();
if (response.isExists()) {
String json = response.getSourceAsString();
}
}
注释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"
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)
System.out.println(cursor.value.getSourceAsMap())
}