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 ...
随机推荐
- SVN版本更新自动通知提醒
当其他用户提交后,如何提示我及时更新代码或版本? 一般情况下,代码的更新时间节点在每天工作开始或有重大功能提交时,所以,不是所有人都对此功能有需求,最好的方式是使用客户端"SVN项目监视器& ...
- python-1-基础认识
前言 将近2020年,python2即将不再更新,但是我们现在的python3也能非常受欢迎的!回顾一下2/3的区别: 1.python2 源码不标准,混乱,重复代码太多, 2.python3 统一 ...
- 【shell脚本】通过位置变量创建Linux账户及密码===addUser.sh
通过位置变量创建Linux账户及密码 脚本内容 [root@VM_0_10_centos shellScript]# vi addUser.sh #!/bin/bash # 通过位置变量创建系统账户及 ...
- java架构之路-(tomcat网络模型)简单聊聊tomcat(二)
上节课我们说到的Tomcat,并且给予了一般的tomcat配置,和配置的作用,提到了HTTP/1.1 也就是我们的网络通讯模型,那么HTTP/1.1又代表什么呢.我们来简答看一下. tomcat有四种 ...
- Linux学习笔记之scp远程拷贝文件
0x00 拷贝本机/home/administrator/test整个目录至远程主机192.168.1.100的/root目录下 代码如下: scp -r /home/administrator/te ...
- yield return,yield break
转自, http://www.cnblogs.com/kingcat/archive/2012/07/11/2585943.html yield return 表示在迭代中下一个迭代时返回的数据,除此 ...
- Vert.x HTTP 服务器与客户端
编写HTTP 服务器与客户端 Vert.x让编写非阻塞的HTTP 服务器与客户端变得非常轻松. 创建HTTP 服务器 缺省状况: HttpServer server = vertx.createHtt ...
- 解决eclipse打开文件乱码
解决办法 需要设置的几处地方为: Window->Preferences->General ->Content Type->Text->JSP 最下面设置为UTF-8 W ...
- vue3.0和2.0的区别,Vue-cli3.0于 8月11日正式发布,更快、更小、更易维护、更易于原生、让开发者更轻松
vue3.0和2.0的区别Vue-cli3.0于 8月11日正式发布,看了下评论,兼容性不是很好,命令有不少变化,不是特别的乐观vue3.0 的发布与 vue2.0 相比,优势主要体现在:更快.更小. ...
- android studio学习----gradle多渠道打包
由于国内Android市场众多渠道,为了统计每个渠道的下载及其它数据统计,就需要我们针对每个渠道单独打包,如果让你打几十个市场的包岂不烦死了,不过有了Gradle,这再也不是事了. 友盟多渠道打包 废 ...