java-api操作ElasticSearch
上两篇文章我们介绍了Elasticsearch以及其相关中间件的部署和基本操作,现在简单的介绍一下java-api连接Es并创建索引。
public class EsConnectTest {
private static Logger logger = LoggerFactory.getLogger(EsConnectTest.class);
public final static String HOST = "127.0.0.1";
public final static int PORT = 9300;//http请求的端口是9200,客户端是9300
public static void main(String[] args) {
List<ArchivesBaseInfo> archivesBaseInfos = new ArrayList<>();
ArchivesBaseInfo archivesBaseInfo = new ArchivesBaseInfo();
archivesBaseInfo.setInfoId("e962774e-5435-4584-8673-d9873feded8e");
archivesBaseInfo.setBoxId("73556be0-44c1-4c7f-9e89-a568cef53bd9");
archivesBaseInfo.setTitle("阿萨德 asd");
archivesBaseInfo.setArchiveNumber("141-WS.4500-10年-办文处-0001");
archivesBaseInfo.setArchiveUserName("斑纹出");
archivesBaseInfo.setReferenceNumber("斑纹虎[2020]66号");
archivesBaseInfo.setCreateTime(new Date());
archivesBaseInfo.setPersonLiable("斑纹");
archivesBaseInfos.add(archivesBaseInfo);
try {
createIndex(archivesBaseInfos);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
public static Client getClient() throws UnknownHostException{
/*Settings settings = Settings.settingsBuilder().put("cluster.name","elasticsearch").build();
TransportClient transportClient = TransportClient.builder().settings(settings).build();
transportClient.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST),PORT));*/
Client client = TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST),PORT));
return client;
}
public static void createIndex(List<ArchivesBaseInfo> archivesBaseInfos) throws UnknownHostException, JsonProcessingException {
Client client = getClient();
if (client.admin().indices().prepareExists("test_index").get().isExists()){
client.admin().indices().prepareDelete("test_index").get();
}
//自定义mapping
String mapperStr = "{ \"goods\" : { \"properties\": { \"id\": { \"type\": \"long\" }, \"name\": {\"type\": \"string\", \"analyzer\": \"ik_max_word\"}, \"regionIds\": {\"type\": \"string\",\"index\": \"not_analyzed\"}}}}";
//使用实体类做mapping
client.admin().indices().prepareCreate("archive").addMapping("content", ArchiveContentVo.class).get();
ObjectMapper objectMapper = new ObjectMapper();
//批量处理request
BulkRequestBuilder requestBuilder = client.prepareBulk();
byte[] json;
for (ArchivesBaseInfo archive:archivesBaseInfos
) {
json = objectMapper.writeValueAsBytes(archive);
requestBuilder.add(new IndexRequest("archive","content",archive.getInfoId() + "").source(json));
}
BulkResponse bulkItemResponses = requestBuilder.get();
//处理错误信息
if (bulkItemResponses.hasFailures()){
logger.error("===================创建索引时出现错误=====================");
int count = 0;
for (BulkItemResponse item:bulkItemResponses
) {
logger.error("发生错误的索引id为:"+item.getId()+",错误信息为:"+item.getFailureMessage());
count++;
}
logger.error("================批量创建索引时出错,共计:"+count+"条=============================");
}
client.close();
}
}