文档章节

Elasticsearch的简单操作

魔法王者安琪拉
 魔法王者安琪拉
发布于 2018/12/10 16:58
字数 520
阅读 14
收藏 0
package com.dongpeng.es;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

public class EsClient {

	private static Logger logger = LoggerFactory.getLogger(EsClient.class);

	private RestHighLevelClient client;
	
	private RestClient restClient;

	/**
	 * 构造连接客户端
	 */
	public EsClient() {
		RestClientBuilder builder = RestClient.builder(new HttpHost("10.136.15.122", 9200, "http"));
		builder.setMaxRetryTimeoutMillis(10000);
		restClient = builder.build();
		client = new RestHighLevelClient(restClient);
	}

	
	/**
	 * 索引数据
	 * 
	 * @throws IOException
	 */
	public void index(Integer ids) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("user", "bellen");
		jsonMap.put("id",ids);
		jsonMap.put("name", new Date());
		jsonMap.put("message", "trying out Elasticsearch");
		
		IndexRequest indexRequest = new IndexRequest("posts", "doc", ids.toString()).source(jsonMap);
		
	    
		
		try {
			// 获取响应结果
			IndexResponse indexResponse = client.index(indexRequest);
			String index = indexResponse.getIndex();
			String type = indexResponse.getType();
			String id = indexResponse.getId();
			long version = indexResponse.getVersion();

			if (indexResponse.getResult() == DocWriteResponse.Result.CREATED) {
				logger.info("doc indexed, index: " + index + ", type:" + type + ",id:" + id + ",version:" + version);
			} else if (indexResponse.getResult() == DocWriteResponse.Result.UPDATED) {
				logger.info("doc updated, index: " + index + ", type:" + type + ",id:" + id + ",version:" + version);
			}
		} catch (ElasticsearchException e) {
			if (e.status() == RestStatus.CONFLICT) {
				logger.error("version conflict");

			}
		} catch (Exception e) {
			logger.error("execute index api failed, " + e.toString());
		}
		
	}
    
	/**
	 * id查找数据
	 * @param id
	 */
	public void findById(String id) {
		GetRequest request = new GetRequest("posts", "doc", id);
		try {
			GetResponse getResponse = client.get(request);
			System.out.println(getResponse.getVersion());
			System.out.println(JSON.toJSONString(getResponse.getSource()));
		} catch (ElasticsearchException e) {
			if (e.status() == RestStatus.NOT_FOUND) {
				System.out.println("没有找到元素");
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	
	}
	
	/**
	 * 删除数据
	 * @param id
	 */
	public void delete(String id) {
		DeleteRequest request = new DeleteRequest("posts", "doc", id);
		DeleteResponse deleteResponse;
		try {
			deleteResponse = client.delete(request);
			if (deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND) {
			    System.out.println("未找到元素");
			}
		} catch (IOException e1) {
			
			e1.printStackTrace();
		}
	
		
	}
	
	/**
	 * 更新数据
	 */
	public void update()  {
		UpdateRequest request = new UpdateRequest(
		        "posts", 
		        "doc",  
		        "1"); 
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("user", "测试");
		jsonMap.put("name", new Date());
		jsonMap.put("message", "trying out Elasticsearch");
		request.doc(jsonMap);
		try {
			client.update(request);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}
	
	/**
	 * search demo
	 */
	public void search() {
		SearchRequest searchRequest = new SearchRequest("posts"); 
		
		SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); 
		sourceBuilder.query(QueryBuilders.matchQuery("message", "trying")); 
		sourceBuilder.from(0); 
		sourceBuilder.size(5); 
		sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
	
		searchRequest.source(sourceBuilder);
		searchRequest.types("doc");
		try {
			SearchResponse searchResponse = client.search(searchRequest);
			SearchHits hits = searchResponse.getHits();
			System.out.println(hits.getTotalHits());
			SearchHit[] searchHits = hits.getHits();
			for (SearchHit hit : searchHits) {
			    System.out.println(JSON.toJSONString(hit.getSource()));
			}
		
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 统计demo
	 */
	public void sum() {

		SearchRequest searchRequest = new SearchRequest("posts"); 
	
		SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); 
		sourceBuilder.query(QueryBuilders.matchQuery("message", "trying")); 
		sourceBuilder.from(0); 
		sourceBuilder.size(5); 
		sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
	    TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("emp_count").field("id");
		sourceBuilder.aggregation(termsAggregationBuilder);
		searchRequest.source(sourceBuilder);
		searchRequest.types("doc");
		
		try {
			
			SearchResponse searchResponse = client.search(searchRequest);
			ParsedLongTerms aggregation = searchResponse.getAggregations().get("emp_count");
			System.out.println(aggregation.getBuckets().size());
			SearchHits hits = searchResponse.getHits();
			System.out.println(hits.getTotalHits());
			SearchHit[] searchHits = hits.getHits();
			for (SearchHit hit : searchHits) {
			    System.out.println(JSON.toJSONString(hit.getSource()));
			}
		
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}
	
	public void close() {
		try {
			restClient.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

 

© 著作权归作者所有

共有 人打赏支持
上一篇: SpringBoot整合es
下一篇: JDK1.8
魔法王者安琪拉
粉丝 78
博文 98
码字总数 32765
作品 0
深圳
程序员
私信 提问
spring-data-elasticsearch 基本案例详解(三)

『 风云说:能分享自己职位的知识的领导是个好领导。 』 运行环境:JDK 7 或 8,Maven 3.0+ 技术栈:SpringBoot 1.5+, Spring Data Elasticsearch 1.5+ ,ElasticSearch 2.3.2 本文提纲 一、...

夜黑人模糊灬
2018/05/13
0
0
Elasticsearch插件一——-head插件安装详解(Elasticsearch教程08)|MVP讲堂

作者:阿里云MVP 铭毅 往期内容: 死磕 Elasticsearch 方法论:普通程序员高效精进的 10 大狠招! Elasticsearch学习,请先看这一篇!(Elasticsearch教程01) Elasticsearch增、删、改、查操...

辰悠
2018/12/14
0
0
高性能Elasticsearch ORM开发库bboss es 5.0.3.7.8发布

bboss es v5.0.3.7.8已发布。bboss elasticsearch是一套基于query dsl语法操作访问分布式搜索引擎elasticsearch的o/r mapping开发库,底层基于es restful api。使用bboss es,可以快速编写出...

bboss
2017/11/16
1K
4
Elastic 在年度用户大会 Elastic{ON} 2018 上发布众多新功能和技术预览

下载超过 2.25 亿次,Elastic 公开 X-Pack 源代码 旧金山 (Elastic{ON} 2018) – 2018 年 2 月 27 日 – Elastic,Elasticsearch 和 Elastic Stack背后的公司,今天宣布其产品累计下载次数达...

Medcl
2018/03/01
0
0
Elasticsearch与Solr搜索引擎选型调研文档

Elasticsearch ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开...

小海bug
2018/06/28
0
0

没有更多内容

加载失败,请刷新页面

加载更多

Java并发编程基础(二)

线程安全与数据同步

chendom
23分钟前
1
0
在Centos7 上安装SVN

在Centos7 上安装SVN 2017年11月16日 17:07:54 crossangles_2017 阅读数:2543 1、安装 使用yum安装非常简单: yum install subversion 2、配置 创建仓库 我们这里在/opt下建立一个名为svn的...

linjin200
25分钟前
1
0
牛津词典 2018 年度词汇 ——「有毒」!

简评:本文并没有「标题党」,牛津词典公布的 2018 年度词汇就是 Toxic. 意为「有毒的」。 2018 was toxic. Toxic 这个词是什么意思呢? 牛津词典(Oxford Dictionaries)在 Word of the Da...

极光推送
31分钟前
1
0
浅谈Service Mesh体系中的Envoy

https://blog.csdn.net/yunqiinsight/article/details/81019255

易野
40分钟前
1
0
嵌入式应用选择合适的微控制器

准备所需硬件接口列表 使用微控制器的基本硬件框图,准备一份微控制器需要支持的所有外设接口的列表。微控制器中有两种常见的接口类型需要列出。第一种是通信接口,这些是外围设备,如USB,S...

linuxCool
48分钟前
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部