elasticsearch 简单demo RestHighLevelClient LowLeveClient
参考:
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.7/java-rest-low.html
www.elastic.co/guide/en/elasticsearch/client/java-rest/6.7/java-rest-high-search.html
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties; import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
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.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.Test; import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject; public class ElasticUtil {
static ObjectMapper mapper = new ObjectMapper();
static RestClient rc=null; public static RestClient getInstance() throws IOException{
if(rc==null) {
return getElasticClient();
}else {
return rc;
}
} /**
* RestHighLevelClient使用详情请参考
* <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.7/java-rest-high-search.html">官方文档</a><br>
* 使用样例见{@link #restHighLevelClient_Demo}
* @return
* @throws IOException
* @since jdk 1.8
*/
public static RestHighLevelClient getRestHighLevelClient() throws IOException{
Properties pro=new Properties();
String filePath=System.getProperty("user.dir")+File.separator+"config/elasticsearch.properties";
try {
pro.load(new FileReader(filePath));
} catch (Exception e) {
e.printStackTrace();
}
String ip=pro.getProperty("ip");
String port=pro.getProperty("port");
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost(ip, Integer.valueOf(port), "http")));
return client;
} /**
* LowLeveClient使用详情请参考
* <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-rest/6.7/java-rest-high-search.html">官方文档</a><br>
* 使用样例见{@link #restLowLeveClient_Demo}
* @return
* @throws IOException
* @since jdk 1.7
*/
public static RestClient getElasticClient() throws IOException{
Properties pro=new Properties();
String filePath=System.getProperty("user.dir")+File.separator+"config/elasticsearch.properties";
try {
pro.load(new FileReader(filePath));
} catch (Exception e) {
e.printStackTrace();
}
String ip=pro.getProperty("ip");
String port=pro.getProperty("port");
return getElasticClient(ip,Integer.valueOf(port),username,passwd);
} public static void main(String[] args) throws IOException {
SearchResponse res=getELKSerach("index1","关键字",0,10,new String[] {"<em>","</em>"});
SearchHits hits = res.getHits();
for(SearchHit hit: hits){
// System.out.println(); //高亮部分
// System.out.println(hit.getScore()); //单个结果集评分
Map<String, Object> map=hit.getSourceAsMap();
// System.out.println(map); //json数据转为map<k,v>
for(Entry<String, HighlightField> ent:hit.getHighlightFields().entrySet()) {
String highl_key=ent.getValue().getName();
String highl_val=ent.getValue().getFragments()[0].toString();
map.put(highl_key, highl_val);
// System.out.println(ent.getKey()+"\t"+ent.getValue());
// System.out.println(ent.getValue().getName()+"\t"+ent.getValue().getFragments()[0]);
}
System.out.println(map);
}
} /**
* @param index 查询的index(类似mysql的datadb)
* @param keyWord 查询的关键字
* @param from 分页参数1
* @param size 分页参数2
* @return
* @throws IOException
*/
public static SearchResponse getELKSerach(String index,String keyWord,int from,int size) throws IOException {
RestHighLevelClient client= getRestHighLevelClient();
SearchRequest searchRequest = new SearchRequest(index);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.queryStringQuery(keyWord));
searchSourceBuilder.timeout(TimeValue.timeValueSeconds(5));
searchSourceBuilder.from(from);
searchSourceBuilder.size(size);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse=client.search(searchRequest, RequestOptions.DEFAULT);
client.close();
return searchResponse;
}
/**
* @param index 查询的index(类似mysql的datadb)
* @param keyWord 查询的关键字
* @param from 分页参数1
* @param size 分页参数2
* @param Highlight 自定义css
* @return
* @throws IOException
*/
public static SearchResponse getELKSerach(String index,String keyWord,int from,int size,String[] Highlight) throws IOException {
RestHighLevelClient client= getRestHighLevelClient();
SearchRequest searchRequest = new SearchRequest(index);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//高亮
if(Highlight.length==2) {
HighlightBuilder highlightBuilder =new HighlightBuilder();
highlightBuilder.field("*");//require_field_match
highlightBuilder.requireFieldMatch(false);
highlightBuilder.preTags(Highlight[0]);
highlightBuilder.postTags(Highlight[1]);
searchSourceBuilder.highlighter(highlightBuilder);
}
//查询
searchSourceBuilder.query(QueryBuilders.queryStringQuery(keyWord));
searchSourceBuilder.timeout(TimeValue.timeValueSeconds(5));
searchSourceBuilder.from(from);
searchSourceBuilder.size(size);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse=client.search(searchRequest, RequestOptions.DEFAULT);
client.close();
return searchResponse;
} void restLowLeveClient_Demo() throws IOException {
RestClient rc =getInstance();
HashMap<String,String> params=new HashMap<>();
HttpEntity entity= getHttpEntityByKeyWord("关键字",0,10);
Response response =rc.performRequest("GET", "/index1/_search",params,entity);
System.out.println(response.getStatusLine().getStatusCode()); String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
JSONObject result = JSONObject.parseObject(responseBody);
JSONObject hists=result.getJSONObject("hits");
System.out.println(hists);
JSONArray list=hists.getJSONArray("hits");
System.out.println(list);
int i= list.size();
System.out.println("all:"+i);
System.out.println(list.get(0));
rc.close();
} void restHighLevelClient_Demo() throws IOException {
RestHighLevelClient client= getRestHighLevelClient();
SearchRequest searchRequest = new SearchRequest("index1");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.queryStringQuery("关键字"));
searchSourceBuilder.timeout(TimeValue.timeValueSeconds(5));
searchSourceBuilder.from(0);
searchSourceBuilder.size(10);
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse=client.search(searchRequest, RequestOptions.DEFAULT);
RestStatus status = searchResponse.status();
System.out.println(status);
SearchHits hits = searchResponse.getHits();
for(SearchHit hit: hits){
System.out.println(hit.getScore());
System.out.println(hit.getSourceAsMap());
}
client.close();
} /*
* 有分页
*/
static HttpEntity getHttpEntityByKeyWord(String keyWord,int from,int size) throws IOException{
String queryString=
"{\r\n" +
" \"from\" : "+from+", \"size\" : "+size+","+
" \"query\": {\r\n" +
" \"multi_match\" : {\r\n" +
" \"query\": \""+keyWord+"\"\r\n" +
" }\r\n" +
" }\r\n" +
"}";
return new NStringEntity(queryString, ContentType.APPLICATION_JSON);
} static HttpEntity getHttpEntityByKeyWord(String keyWord) throws IOException{
String queryString=
"{\r\n" +
" \"query\": {\r\n" +
" \"multi_match\" : {\r\n" +
" \"query\": \""+keyWord+"\"\r\n" +
" }\r\n" +
" }\r\n" +
"}";
return new NStringEntity(queryString, ContentType.APPLICATION_JSON);
}
/**
* 获取elastic的client的信息
* @param ip
* @param port
* @param usename
* @param passwd
* @return
*/
public static RestClient getElasticClient(String ip, Integer port, String usename, String passwd) {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(usename, passwd));
RestClient restClient = RestClient.builder(new HttpHost(ip, port, "http"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
httpClientBuilder.disableAuthCaching();
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
}).build();
return restClient;
} public static HttpEntity entiy2HttpEntity(Object ent) throws JsonGenerationException, JsonMappingException, IOException{
String jsonString = mapper.writeValueAsString(ent);
HttpEntity entity = new NStringEntity(jsonString, ContentType.APPLICATION_JSON);
return entity;
} /**
* 批处理用
* @param list
* @return
* @throws JsonGenerationException
* @throws JsonMappingException
* @throws IOException
*/
public static HttpEntity entiyList2HttpEntity(List<Object> list,String index,String type) throws JsonGenerationException, JsonMappingException, IOException{
String tmp="{ \"index\": { \"_index\": \""+index+"\", \"_type\": \""+type+"\" }}";
StringBuilder sb=new StringBuilder();
for (Object ent : list) {
String jsonString = mapper.writeValueAsString(ent);
sb.append(tmp).append("\n").append(jsonString).append("\n");
} HttpEntity entity = new NStringEntity(sb.toString(), ContentType.APPLICATION_JSON);
return entity;
} public static String Response2String( Response response) throws IOException{
return EntityUtils.toString(response.getEntity());
} }
elasticsearch 简单demo RestHighLevelClient LowLeveClient的更多相关文章
- 设计模式之单例模式的简单demo
/* * 设计模式之单例模式的简单demo */ class Single { /* * 创建一个本类对象. * 和get/set方法思想一样,类不能直接调用对象 * 所以用private限制权限 * ...
- Spring的简单demo
---------------------------------------- 开发一个Spring的简单Demo,具体的步骤如下: 1.构造一个maven项目 2.在maven项目的pom.xml ...
- 使用Spring缓存的简单Demo
使用Spring缓存的简单Demo 1. 首先创建Maven工程,在Pom中配置 <dependency> <groupId>org.springframework</g ...
- Managed DirectX中的DirectShow应用(简单Demo及源码)
阅读目录 介绍 准备工作 环境搭建 简单Demo 显示效果 其他 Demo下载 介绍 DirectX是Microsoft开发的基于Windows平台的一组API,它是为高速的实时动画渲染.交互式音乐和 ...
- angular实现了一个简单demo,angular-weibo-favorites
前面必须说一段 帮客户做了一个过渡期的项目,唯一的要求就是速度,我只是会点儿基础的php,于是就用tp帮客户做了这个项目.最近和客户架构沟通,后期想把项目重新做一下,就用现在最流行的技术,暂时想的使用 ...
- NEST.net Client For Elasticsearch简单应用
NEST.net Client For Elasticsearch简单应用 由于最近的一个项目中的搜索部分要用到 Elasticsearch 来实现搜索功能,苦于英文差及该方面的系统性资料不好找,在实 ...
- Solr配置与简单Demo[转]
Solr配置与简单Demo 简介: solr是基于Lucene Java搜索库的企业级全文搜索引擎,目前是apache的一个项目.它的官方网址在http://lucene.apache.org/sol ...
- 二维码简单Demo
二维码简单Demo 一.视图 @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name=&qu ...
- android JNI 简单demo(2)它JNI demo 写
android JNI 简单demo(2)它JNI demo 写 一.搭建Cygwin 环境:http://blog.csdn.net/androidolblog/article/details/25 ...
随机推荐
- Go Modules使用教程(3分钟学会)
前言 随着Go 1.13发布,GOPROXY默认值proxy.golang.org在中国大陆不能被访问. 七牛云顺势推出goproxy.cn,以利于中国开发者更好使用Go Modules,它是非盈利性 ...
- 在Ubuntu18.04.2LTS上安装搜狗输入法
在Ubuntu18.04.2LTS上安装搜狗输入法 一.前言 最近项目使用到了Linux系统,因此就安装了Ubuntu18.04.2这个最新的LTS的OS.整体的使用效果是不敢恭维的,特别是使用虚拟机 ...
- Vue.js 源码分析(三) 基础篇 模板渲染 el、emplate、render属性详解
Vue有三个属性和模板有关,官网上是这样解释的: el ;提供一个在页面上已存在的 DOM 元素作为 Vue 实例的挂载目标 template ;一个字符串模板作为 Vue 实例的标识使用.模板将会 ...
- Linux查找文件夹下包含某字符的所有文件
Linux grep 命令用于查找文件里符合条件的字符串.grep 指令用于查找内容包含指定的范本样式的文件,如果发现某文件的内容符合所指定的范本样式,预设 grep 指令会把含有范本样式的那一列显示 ...
- 全链路跟踪TraceId
数据库主键:标示唯一一条数据,譬如唯一商品,唯一订单 全局事务ID:实现分布式事务一致性的必备良药 请求ID:requestId,seesionId,标示一个请求或者一次会话的生命周期 身份证ID:代 ...
- Kubernetes service 使用定义
Kubernetes service 使用定义 介绍说明 • 防止Pod失联• 定义一组Pod的访问策略• 支持ClusterIP,NodePort以及LoadBalancer三种类型• Servic ...
- 自动轮播swiper css实现
@keyframes scale { 0% { transform: scale(1, 1); opacity: 0.5; z-index:; transition: opacity z-index ...
- C# NPOI Export DataTable C# NPOI导出DataTable 单元格自适应大小
1.Install-Package NPOI -v 2.4.0 2. using NPOI.XSSF; using NPOI.XSSF.UserModel; using NPOI.SS.UserMod ...
- linq,创建数据库,插入数据,newDB.CreateDatabase();newDB.tb2.InsertOnSubmit(stu); newDB.SubmitChanges();
using System.Data.Linq;using System.Data.Linq.Mapping; namespace ConsoleApplication1388{ class Progr ...
- 高强度学习训练第一天总结:Java内存区域
---恢复内容开始--- 程序计数器: 程序计数器(Program Counter Register) 是一块较小的空间,他可以看作是当前线程所执行的字节码的行号指示器.在虚拟机的概念模型里(仅是概念 ...