在线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(); } }
原文地址:https://www.cnblogs.com/xyhero/p/9339189.html
时间: 2024-11-07 12:41:01