使用java如何操作elasticsearch?簡單示例。
阿新 • • 發佈:2018-07-20
exception 工具類 del ets response src res artifact ket
在線API:
https://www.elastic.co/guide/en/elasticsearch/client/java-api/2.4/transport-client.html
教程:
http://blog.java1234.com/blog/articles/345.html
註意:
不同版本的ES API差別較大,引入jar包版本一定要和生產保持一致。工具類及使用方法可以參考備件系統項目:源碼見GitHub
工具類及使用方法可以參考備件系統項目:源碼見GitHub
引入jar包:
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.4.0</version>
</dependency>
寫測試類:
package com.sxt.es.test; import java.net.InetAddress; import java.util.Date; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.xcontent.XContentFactory;public class Testes { private static String host="192.168.136.131"; // 服務器地址 private static int port=9300; // 端口 public static void main(String[] args) throws Exception { TransportClient client = TransportClient.builder().build() .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(Testes.host), Testes.port)); IndexResponse response =client.prepareIndex("twitter", "tweet", "1") .setSource(XContentFactory.jsonBuilder() .startObject() .field("user", "kimchy") .field("postDate", new Date()) .field("message", "trying out Elasticsearch") .endObject() ) .get(); System.out.println("索引名稱:"+response.getIndex()); System.out.println("類型:"+response.getType()); System.out.println("文檔ID:"+response.getId()); // 第一次使用是1 client.close(); } }
使用java如何操作elasticsearch?簡單示例。