Elasticsearch系列(七)

编程入门 行业动态 更新时间:2024-10-24 08:30:36

Elasticsearch<a href=https://www.elefans.com/category/jswz/34/1770787.html style=系列(七)"/>

Elasticsearch系列(七)

1.创建maven项目,pom.xml文件中增加如下配置:

<dependencies><dependency><groupId>org.elasticsearch.client</groupId><artifactId>transport</artifactId><version>6.4.0</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency>
</dependencies>
<build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.2</version><configuration><source>1.8</source><target>1.8</target><encoding>UTF-8</encoding></configuration></plugin></plugins>
</build>

java代码调用:

package com.es.elasticsearch;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import net.sf.json.JSONObject;import java.io.IOException;
import java.InetAddress;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearchmon.settings.Settings;
import org.elasticsearchmon.transport.TransportAddress;
import org.elasticsearchmon.xcontent.XContentBuilder;
import org.elasticsearchmon.xcontent.XContentFactory;
import org.elasticsearchmon.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;public class ElasticsearchTest_1 {private Logger logger = LoggerFactory.getLogger(ElasticsearchTest_1.class);public final static String HOST="127.0.0.1";//http请求的端口是9200,客户端是9300public final static int PORT = 9300; public final static String CLUSTERNAME = "elasticsearch";public static TransportClient getConnection() throws Exception {Settings settings = Settings.builder().put("client.transport.sniff", true) //增加嗅探机制,找到ES集群.put("cluster.name", CLUSTERNAME)  // 设置集群名称.put("thread_pool.search.size", 20)// 增加线程池个数,暂时设为20.build();// 创建clientTransportClient client = new PreBuiltTransportClient(settings).addTransportAddresses(new TransportAddress(InetAddress.getByName(HOST), PORT));return client;}/** 添加* 索引和类型是必需的,而id部分是可选的。如果不指定ID,ElasticSearch会为我们生成一个ID。 */  public void add() throws Exception{try {XContentBuilder content = XContentFactory.jsonBuilder().startObject().field("name","daniel").field("age",20).field("job","coder").endObject();String index = "data";   // 索引值String type ="person";   // 类型String id="1";           // id值TransportClient client = this.getConnection();IndexResponse iresp = client.prepareIndex(index, type,id).setSource(content).get();client.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** 添加索引:传入json字符串* id 自动创建* * */public void addJsonstr() throws Exception{String jsonstr = "{\"userName\":\"Tom\",\"date\":\"2018-11-7\",\"msg\":\"where are you\"}";TransportClient client = this.getConnection();IndexResponse iresp = client.prepareIndex("chat", "msg").setSource(jsonstr,XContentType.JSON).get();client.close();System.err.println(iresp.getIndex());System.err.println(iresp.getId());System.out.println(iresp.status());}/** 添加索引:传入json* * */public void addJSON() throws Exception{JSONObject json = new JSONObject();json.put("userName", "allen");json.put("date", new Date().toString());json.put("msg", "hello  allen");TransportClient client = this.getConnection();IndexResponse iresp = client.prepareIndex("chat", "msg","3").setSource(json,XContentType.JSON).get();client.close();System.err.println(iresp.getIndex());System.err.println(iresp.getId());System.out.println(iresp.status());}/** 创建索引-传入Map对象* * */public void addMap() throws Exception{Map<String, Object> map = new HashMap<String,Object>();map.put("userName", "Daniel");map.put("sendDate", new Date());map.put("msg", "hello Daniel");TransportClient client = this.getConnection();IndexResponse response = client.prepareIndex("momo", "msg","1").setSource(map).get();logger.info("map索引名称:" + response.getIndex() + "\n map类型:" + response.getType()+ "\n map文档ID:" + response.getId() + "\n当前实例map状态:" + response.status());}/*  * 获取数据*/  public void get(String index,String type,String id) throws Exception{TransportClient client = this.getConnection();GetResponse  result = client.prepareGet(index,type,id).get();System.out.println(result.getSourceAsString());System.out.println(result.getType());System.out.println(result.getVersion());System.err.println(result.getIndex());System.err.println(result.getId());client.close();}/*  * 更新*/  public void update() throws Exception{XContentBuilder content = XContentFactory.jsonBuilder().startObject();content.field("age",22);content.field("job","boss");content.endObject();UpdateRequest request = new UpdateRequest("data","person","1");request.doc(content);TransportClient client = this.getConnection();UpdateResponse resp = client.update(request).get();client.close();}/*  * 删除*/  public void delete() throws Exception{TransportClient client = this.getConnection();DeleteResponse  response = client.prepareDelete("data","person","1").get();client.close();System.out.println(response.getResult());}/*  * 关闭*/  public static void closeConnect(TransportClient client){if(null !=client){client.close();}}public static void main(String[] args) throws Exception {/*TransportClient  client = getConnection();System.out.println(client.toString());System.out.println(client.nodeName());*/ElasticsearchTest_1 t = new ElasticsearchTest_1();//      t.add();
//    t.get();//    t.update();
//    t.get();//    t.delete();
//    t.get("data","person","1");//    t.addJsonstr();
//    t.get("chat", "msg","5jbh7GYB_P4tFfCC1ruQ");
//    t.get("chat", "msg","5zbl7GYB_P4tFfCCpLt1");//    t.addJSON();t.get("chat", "msg","3");//    t.addMap();
//    t.get("momo", "msg","1");}}

请关注我微信公众号:

更多推荐

Elasticsearch系列(七)

本文发布于:2024-03-08 21:31:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1722449.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:系列   Elasticsearch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!