import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
/**
* @Description :ElasticSearch常用操作Java api
* @Author: lyw
* @Date: 2019/1/15 11:27
* @Version 1.0
*/
public class ESTest {
// es的连接
private Client client;
@Before
public void getClient() throws Exception {
// 配置请求es的信息
// 注意:你的es集群名称如果是elasticsearch,就不用该配置了
final HashMap<String, String> map = new HashMap<>();
map.put("cluster.name", "es");
final Settings.Builder settings = Settings.builder().put(map);
// es的java api提供的端口为9300
// 可以再添加多个节点,目的就是为了其中一个实例出现网络问题的时候,会自动切换请求另一个实例
client = TransportClient.builder().settings(settings).build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("hadoop01"), 9300))
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("hadoop02"), 9300))
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("hadoop03"), 9300));
}
/**
* 使用json来创建文档并写入数据
*/
@Test
public void createDoc_1() {
// json字符串
String source = "{" +
"\"id\":\"1\"," +
"\"title\":\"ElasticSearch是一个基于Lucene的搜索服务器\"," +
"\"content\":\"它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口\"}";
// 创建文档,定义索引、文档类型、主键id
final IndexResponse indexResponse = client.prepareIndex("blog", "article", "1").setSource(source).get();// 也可以用 execute().actionGet()
// 获取响应的信息
System.out.println("index:" + indexResponse.getIndex());
System.out.println("type:" + indexResponse.getType());
System.out.println("id:" + indexResponse.getId());
System.out.println("version:" + indexResponse.getVersion());
System.out.println("是否创建成功:
ElasticSearch常用操作Java api
最新推荐文章于 2024-05-30 16:10:57 发布