es模糊查询 java_java使用elasticsearch进行模糊查询之must使用
java使用elasticsearch进行多个条件模糊查询
文章说明:
1、本篇文章,本人会从java连接elasticsearch到查询结果生成并映射到具体实体类(涵盖分页功能)
2、代码背景:elasticsearch版本为:5.2.0;
3、本人以下代码是分别从两个索引中查询数据,再将两个数据进行整合,如果大家只需要分组查询,那么则选取文章中的分组查询部分代码
4、本人的实体类主要是按照layUI分页框架进行设计;实体大家可以根据自己的具体需求进行设计
一、java连接elasticsearch工具类
public classESClientConnectionUtil {public static TransportClient client=null;public final static String HOST = "192.168.200.200"; //服务器部署ip 根据自己ip进行更改
public final static Integer PORT = 9301; //端口
public staticTransportClient getESClient(){
System.setProperty("es.set.netty.runtime.available.processors", "false");if (client == null) {synchronized (ESClientConnectionUtil.class) {try{//设置集群名称
Settings settings = Settings.builder().put("cluster.name", "es5").put("client.transport.sniff", true).build();//创建client
client = new PreBuiltTransportClient(settings).addTransportAddress(newInetSocketTransportAddress(InetAddress.getByName(HOST), PORT));
}catch(Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
}returnclient;
}public staticTransportClient getESClientConnection(){if (client == null) {
System.setProperty("es.set.netty.runtime.available.processors", "false");try{//设置集群名称
Settings settings = Settings.builder().put("cluster.name", "es5").put("client.transport.sniff", true).build();//创建client
client = new PreBuiltTransportClient(settings).addTransportAddress(newInetSocketTransportAddress(InetAddress.getByName(HOST), PORT));
}catch(Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}returnclient;
}//判断索引是否存在
public static booleanjudgeIndex(String index){
client=getESClientConnection();
IndicesAdminClient adminClient;//查询索引是否存在
adminClient=client.admin().indices();
IndicesExistsRequest request= newIndicesExistsRequest(index);
IndicesExistsResponse responses=adminClient.exists(request).actionGet();if(responses.isExists()) {return true;
}return false;
}
}
二、实体类
(一)分页实体总类
public classKnowledgeTopicListDTO {private Long totalCount;//总条数
private Integer page;//页数
private Integer limit;//每页查询条数
private List topicDTOList;//每页显示数据的对象集合
publicLong getTotalCount() {returntotalCount;
}public voidsetTotalCount(Long totalCount) {this.totalCount =totalCount;
}publicInteger getPage() {returnpage;
}public voidsetPage(Integer page) {this.page =page;
}publicInteger getLimit() {returnlimit;
}public voidsetLimit(Integer limit) {this.limit =limit;
}public ListgetTopicDTOList() {returntopicDTOList;
}public void setTopicDTOList(ListtopicDTOList) {this.topicDTOList =topicDTOList;
}
}
(二)页面显示数据对象实体
public classKnowledgeTopicDTO {private Long id;//知识主题id
private String name;//知识主题名称
private Boolean active;//有效无效 true,false
private String activeString;//有效无效
private Boolean noSubscription;//是否需要订阅 true,false
private String noSubscriptionString;//是否需要订阅
private Long quantity;//数据量
privateString _id;privateString ids;publicString getIds() {returnids;
}public voidsetIds(String ids) {this.ids =ids;
}publicLong getId() {returnid;
}public voidsetId(Long id) {this.id =id;
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}publicBoolean getActive() {returnactive;
}public voidsetActive(Boolean active) {this.active =active;
}publicString getActiveString() {returnactiveString;
}public voidsetActiveString(String activeString) {this.activeString =activeString;
}publicBoolean getNoSubscription() {returnnoSubscription;
}public voidsetNoSubscription(Boolean noSubscription) {this.noSubscription =noSubscription;
}publicString getNoSubscriptionString() {returnnoSubscriptionString;
}public voidsetNoSubscriptionString(String noSubscriptionString) {this.noSubscriptionString =noSubscriptionString;
}publicLong getQuantity() {returnquantity;
}public voidsetQuantity(Long quantity) {this.quantity =quantity;
}publicString get_id() {return_id;
}public voidset_id(String _id) {this._id =_id;
}
}
三、后台service层代码
publicKnowledgeTopicListDTO selectTopicByName(String name, Integer page, Integer limit) {
SearchResponse searchResponse=null;
Map map = new HashMap<>();
TransportClient transportClient=ESClientConnectionUtil.getESClientConnection();
SearchRequestBuilder requestBuilder= client.prepareSearch("knowledge").setTypes("knowledge_theme");//声明where条件
BoolQueryBuilder qbs =QueryBuilders.boolQuery();/**此处使用模糊匹配查询 类比数据库中 like*/QueryBuilder qb1= QueryBuilders.matchPhraseQuery("name", name);
BoolQueryBuilder bqb1=QueryBuilders.boolQuery().must(qb1);
qbs.must(bqb1);
requestBuilder.setQuery(qbs);int num=limit*(page-1);
SearchResponse response= requestBuilder.setFrom(0).setSize(10).execute().actionGet();//获取总条数//long totalCount = searchResponse.getHits().getTotalHits();
List list = new ArrayList();for(SearchHit hit : response.getHits().getHits()) {//获取到当前页的数据
JSONObject obj = new JSONObject().fromObject(hit.getSourceAsString());//将json字符串转换为json对象
KnowledgeTopicDTO topic = (KnowledgeTopicDTO) JSONObject.toBean(obj, KnowledgeTopicDTO.class);//将建json对象转换为Person对象
list.add(topic);
}//查询主题总数
Terms terms= ESGroupByUtil.GroupByOne(client,"hottopic","hot","sum","tasktitleid");
list= groupList(list,terms);//调用组合主题总数方法
KnowledgeTopicListDTO knowledgeTopicListDTO = newKnowledgeTopicListDTO();
knowledgeTopicListDTO.setLimit(limit);
knowledgeTopicListDTO.setPage(page);
knowledgeTopicListDTO.setTopicDTOList(list);returnknowledgeTopicListDTO;
}
五、根据单个字段分组查询
public classESGroupByUtil {/***@description: 根据单个字段分组求和
*@author:cyb
*@date: 2018-11-16 17:31
*@param: client ES连接
*@param: indices 索引
*@param: types 类型
*@param: alias 分组求和别名
*@param: DomName 分组目标字段名
*@return: org.elasticsearch.search.aggregations.bucket.terms.Terms*/
public staticTerms GroupByOne(TransportClient client,String indices,String types,String alias,String DomName){
SearchRequestBuilder sbuilder=client.prepareSearch(indices).setTypes(types);
TermsAggregationBuilder termsBuilder=AggregationBuilders.terms(alias).field(DomName);
sbuilder.addAggregation(termsBuilder);
SearchResponse responses=sbuilder.execute().actionGet();
Terms terms=responses.getAggregations().get(alias);returnterms;
}
}
六 、将分组查询的数据进行整合到已查询到的集合中
/***@description:将查询的总数合并到list中
*@author:cyb
*@date: 2018-11-16 17:51
*@param: list
*@param: terms
*@return: java.util.List*/
public List groupList(Listlist,Terms terms){
List lists = new ArrayList<>();for(int i=0;i
String id =terms.getBuckets().get(i).getKey().toString();//id
Long sum =terms.getBuckets().get(i).getDocCount();//数量
BsKnowledgeInfoDTO bsKnowledgeInfoDTO1 = newBsKnowledgeInfoDTO();
bsKnowledgeInfoDTO1.setId(id);
bsKnowledgeInfoDTO1.setSum(sum);
lists.add(bsKnowledgeInfoDTO1);
System.out.println("=="+ terms.getBuckets().get(i).getDocCount()+"------"+terms.getBuckets().get(i).getKey());
}for(int i=0;i
list.get(j).setQuantity(lists.get(i).getSum());
}
}
}returnlist;
}
总结:以上代码是本人的亲自测试通过的,分页后期建议大家不用使用from,size格式,当数据量超过1w的时候,速度会越来越慢,并可能造成宕机。
es模糊查询 java_java使用elasticsearch进行模糊查询之must使用相关推荐
- wildcard java_java操作elasticsearch实现前缀查询、wildcard、fuzzy模糊查询、ids查询
1.前缀查询(prefix) //prefix前缀查询 @Testpublic void test15() throwsUnknownHostException {//1.指定es集群 cluster ...
- es java 模糊查询_java使用elasticsearch进行模糊查询-已在项目中实际应用
java使用elasticsearch进行模糊查询 使用环境上篇文章本人已书写过,需要maven坐标,ES连接工具类的请看上一篇文章,以下是内容是笔者在真实项目中运用总结而产生,并写的是主要方法和思路 ...
- java对es做聚合查询_java操作elasticsearch实现聚合查询
1.max 最大值 //max 求最大值 @Test public void test30() throws UnknownHostException{ //1.指定es集群 cluster.name ...
- Elasticsearch索引和查询性能调优的21条建议【下】
Elasticsearch是一款流行的分布式开源搜索和数据分析引擎,具备高性能.易扩展.容错性强等特点.它强化了Apache Lucene的搜索能力,把掌控海量数据索引和查询的方式提升到一个新的层次. ...
- Elasticsearch实战——地理位置查询
Elasticsearch实战--地理位置查询 文章目录 Elasticsearch实战--地理位置查询 1. 半径查询(geo_distance query) 2. 指定矩形内的查询(geo_bou ...
- java操作elasticsearch实现前缀查询、wildcard、fuzzy模糊查询、ids查询
1.前缀查询(prefix) //prefix前缀查询 @Testpublic void test15() throws UnknownHostException {//1.指定es集群 cluste ...
- SpringBoot+Mybatis+Elasticsearch 实现模糊分页查询并标记关键字
SpringBoot 整合 Elasticsearch 实现模糊分页查询并标记关键字 一.概述 & 介绍 Elasticsearch 是基于 Lucense 技术的搜索引擎(服务器),将数据进 ...
- Java分词工具模糊查询_Java如何使用elasticsearch进行模糊查询
这篇文章主要介绍了java如何使用elasticsearch进行模糊查询,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 使用环境上篇文章本人已书写过 ...
- 【全文搜索引擎】Elasticsearch之模糊查询
wildcard查询 通配符查询允许我们在查询值中使用*和?等通配符.此外,通配符查询跟词条查询在内容方面非常类似.可以发送一下查询,来匹配所有包含cr?me词条的文档,这里?表示任意字符: {&qu ...
- es查询语句拼接 java_JAVA使用ElasticSearch查询in和not in的实现方式
JAVA使用ElasticSearch查询in和not in的实现方式 发布时间:2020-08-22 16:03:11 来源:脚本之家 阅读:119 作者:执笔记忆的空白 ElasticSearch ...
最新文章
- java中 resource_Java从Resource中读取文本文件
- 再学 GDI+[81]: TGPImage(1) - 显示图像
- oracle更新快捷方式的错误,oracle 11g数据库启动错误总结
- Web笔记-html中svg的基本使用
- Tomcat的部署+第一个Servlet
- Flutter进阶—质感设计之模态底部面板
- chart控件支持鼠标滚轮放大缩小_强大的鼠标侧键功能设置工具:X-Mouse Button Control...
- 【Unity3d】【项目学习心得】从资源服务器下载资源(二)
- 总是通过加班,来完成工作,那都是假象
- jsp mysql 鲜花_jsp+servlet+mysql实现的在线鲜花商城源码附带视频指导运行教程
- [20160831]关于数据块Checksum.txt
- 维修计算机小能人,电脑小能人作文「精选」
- 腾讯云人脸识别 报错 Entry name ‘assets/detector/wb_net_2_bin.rpnproto‘ collided
- window10安装minio
- 计算机教学能力提升体会,学习《信息技术助力教学能力提高》感悟
- cuda安装正常,nvcc -V却没有任何显示
- 一个可以免费下载O Reilly的书籍的地方
- virgo tomcat
- Python | 英雄联盟游戏数据分析
- 工信部打击通讯信息诈骗取得阶段性进展
热门文章
- 国产系统银河麒麟(龙芯MIPS)远程访问自研windows程序
- 计算机基金经理排名,科班出身的基金经理业绩一定比非科班的好吗?
- windows x64和x86区别
- GIS实验之制作地形地貌图
- 刑法285条非法获取计算机信息数据,刑法285条量刑标准,提供侵入计算机系统工具罪,并被拘役...
- Android material design 之 BottomSheet基础入门
- iOS App配置 Universal Link通用链接
- [11g](ALTER SYSTEM SUSPEND)Suspending and Resuming a Database
- python 英语拼写-Python实现单词拼写检查
- hive on spark : 使用load data 命令将hdfs上数据覆写到hive表中报错:could not be cleaned up解决方法