spring 操作elasticsearch查询使用方法
短信预约 -IT技能 免费直播动态提醒
最近学习了一下elasticsearch使用,网上的资料又很少,真是一个头两个大。好歹最后终于了解了。留个笔记做日后查询。
package com.gooddeep.dev.elasticsearch.commons.dao; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.elasticsearch.action.ActionFuture; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.Client; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.text.Text; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.highlight.HighlightBuilder; import org.elasticsearch.search.highlight.HighlightBuilder.Field; import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.SortOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.SearchResultMapper; import org.springframework.data.elasticsearch.core.query.Criteria; import org.springframework.data.elasticsearch.core.query.CriteriaQuery; import org.springframework.data.elasticsearch.core.query.DeleteQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.data.elasticsearch.core.query.StringQuery; import org.springframework.stereotype.Component; import com.gooddeep.dev.core.helper.PropertyHelper; import com.gooddeep.dev.core.helper.UuidHelper; import com.gooddeep.dev.core.model.BasePage; import com.gooddeep.dev.elasticsearch.commons.model.EsBaseBean; import com.gooddeep.dev.elasticsearch.commons.service.EsBaseService; @Component("esBaseDao") public abstract class EsBaseDaoImpl<T> implements EsBaseDao<T> { private Logger logger = LoggerFactory.getLogger(EsBaseService.class); @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Autowired private Client esClient; public boolean insertOrUpdate(List<T> tList) { List<IndexQuery> queries = new ArrayList<IndexQuery>(); for (T t : tList) { String id = ((EsBaseBean) t).getId(); if (id == null) { id = UuidHelper.getRandomUUID(); ((EsBaseBean) t).setId(id); } IndexQuery indexQuery = new IndexQueryBuilder().withId(id).withObject(t).build(); queries.add(indexQuery); } elasticsearchTemplate.bulkIndex(queries); return true; } public boolean insertOrUpdate(T t) { String id = ((EsBaseBean) t).getId(); if (id == null) { id = UuidHelper.getRandomUUID(); ((EsBaseBean) t).setId(id); } try { IndexQuery indexQuery = new IndexQueryBuilder().withId(id).withObject(t).build(); elasticsearchTemplate.index(indexQuery); return true; } catch (Exception e) { logger.error("insert or update user info error.", e); return false; } } public boolean deleteById(String id) { try { elasticsearchTemplate.delete(getEntityClass(), id); return true; } catch (Exception e) { logger.error("delete " + getEntityClass() + " by id " + id + " error.", e); return false; } } @Override public boolean deleteByIds(List<String> idList) { try { CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria()); criteriaQuery.setIds(idList); elasticsearchTemplate.delete(criteriaQuery, getEntityClass()); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public boolean deleteByQuery(Map<String,Object> filedContentMap) { try { DeleteQuery dq = new DeleteQuery(); BoolQueryBuilder qb=QueryBuilders. boolQuery(); if(filedContentMap!=null) for (String key : filedContentMap.keySet()) {//字段查询 qb.must(QueryBuilders.matchQuery(key,filedContentMap.get(key))); } dq.setQuery(qb);; elasticsearchTemplate.delete(dq, getEntityClass());; return true; } catch (Exception e) { e.printStackTrace(); return false; } } public boolean ping() { try { ActionFuture<ClusterHealthResponse> health = esClient.admin() .cluster().health(new ClusterHealthRequest()); ClusterHealthStatus status = health.actionGet().getStatus(); if (status.value() == ClusterHealthStatus.RED.value()) { throw new RuntimeException( "elasticsearch cluster health status is red."); } return true; } catch (Exception e) { logger.error("ping elasticsearch error.", e); return false; } } @Override public BasePage<T> queryPage(Map<String,Object> filedContentMap, final List<String> heightFields, String sortField, SortOrder order, BasePage<T>basePage) { Field[] hfields=new Field[0]; if(heightFields!=null) { hfields = new Field[heightFields.size()]; for (int i = 0; i < heightFields.size(); i++) { hfields[i] = new HighlightBuilder.Field(heightFields.get(i)).preTags("<em style='color:red'>").postTags("</em>").fragmentSize(250); } } NativeSearchQueryBuilder nsb = new NativeSearchQueryBuilder().withHighlightFields(hfields);//高亮字段 if (sortField != null && order != null)//排序 nsb.withSort(new FieldSortBuilder(sortField).ignoreUnmapped(true).order(order)); if (basePage != null)//分页 nsb.withPageable(new PageRequest(basePage.getPageNo(), basePage.getPageSize())); BoolQueryBuilder qb=QueryBuilders. boolQuery(); for (String key : filedContentMap.keySet()) {//字段查询 qb.must(QueryBuilders.matchQuery(key,filedContentMap.get(key))); } //userKey=78e48b85e94911e0d285f4eec990d556 //fa6e9c5bb24a21807c59e5fd3b609e12 nsb.withQuery(qb); SearchQuery searchQuery = nsb.build();//查询建立 Page<T> page = null; if (heightFields!=null&&heightFields.size() > 0) {//如果设置高亮 page = elasticsearchTemplate.queryForPage(searchQuery, getEntityClass(), new SearchResultMapper() { @SuppressWarnings("unchecked") @Override public <T> Page<T> mapResults(SearchResponse response,Class<T> clazz, Pageable pageable) { List<T> chunk = new ArrayList<T>(); for (SearchHit searchHit : response.getHits()) { if (response.getHits().getHits().length <= 0) { return null; } Map<String, Object> entityMap = searchHit.getSource(); for (String highName : heightFields) { Text text[]=searchHit.getHighlightFields().get(highName).fragments(); if(text.length>0) { String highValue = searchHit.getHighlightFields().get(highName).fragments()[0].toString(); entityMap.put(highName, highValue); } } chunk.add((T) PropertyHelper.getFansheObj( getEntityClass(), entityMap)); } if (chunk.size() > 0) { return new PageImpl<T>((List<T>) chunk); } return new PageImpl<T>(new ArrayList<T>()); } }); } else//如果不设置高亮 { logger.info("#################"+qb.toString()); page = elasticsearchTemplate.queryForPage(searchQuery,getEntityClass()); } // List<T> ts = page.getContent(); basePage.setTotalRecord(page.getTotalElements()); basePage.setResults(page.getContent()); return basePage; } @Override public List<T> queryList(Map<String, Object> filedContentMap,final List<String> heightFields, String sortField, SortOrder order) { Field[] hfields=new Field[0]; if(heightFields!=null) { hfields = new Field[heightFields.size()]; for (int i = 0; i < heightFields.size(); i++) { //String o="{\"abc\" : \"[abc]\"}"; hfields[i] = new HighlightBuilder.Field(heightFields.get(i)).preTags("<em>").postTags("</em>").fragmentSize(250); } } NativeSearchQueryBuilder nsb = new NativeSearchQueryBuilder().withHighlightFields(hfields);//高亮字段 if (sortField != null && order != null)//排序 nsb.withSort(new FieldSortBuilder(sortField).ignoreUnmapped(true).order(order)); BoolQueryBuilder qb=QueryBuilders. boolQuery(); for (String key : filedContentMap.keySet()) {//字段查询 qb.must(QueryBuilders.matchQuery(key,filedContentMap.get(key))); } nsb.withQuery(qb); SearchQuery searchQuery = nsb.build();//查询建立 Page<T> page = null; if (heightFields!=null&&heightFields.size() > 0) {//如果设置高亮 page = elasticsearchTemplate.queryForPage(searchQuery, getEntityClass(), new SearchResultMapper() { @SuppressWarnings("unchecked") @Override public <T> Page<T> mapResults(SearchResponse response,Class<T> clazz, Pageable pageable) { List<T> chunk = new ArrayList<T>(); for (SearchHit searchHit : response.getHits()) { if (response.getHits().getHits().length <= 0) { return null; } Map<String, Object> entityMap = searchHit.getSource(); for (String highName : heightFields) { String highValue = searchHit.getHighlightFields().get(highName).fragments()[0].toString(); entityMap.put(highName, highValue); } chunk.add((T) PropertyHelper.getFansheObj(getEntityClass(), entityMap)); } if (chunk.size() > 0) { return new PageImpl<T>((List<T>) chunk); } return null; } }); } else//如果不设置高亮 page = elasticsearchTemplate.queryForPage(searchQuery,getEntityClass()); return page.getContent(); } public T queryById(String id) { StringQuery stringQuery = new StringQuery("id=" + id); T t = elasticsearchTemplate.queryForObject(stringQuery, getEntityClass()); return t; } public ElasticsearchTemplate getElasticsearchTemplate() { return elasticsearchTemplate; } public Client getEsClient() { return esClient; } public abstract Class<T> getEntityClass(); public abstract void putClassMapping(); }
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
spring 操作elasticsearch查询使用方法
下载Word文档到电脑,方便收藏和打印~
下载Word文档
猜你喜欢
spring 操作elasticsearch查询使用方法
最近学习了一下elasticsearch使用,网上的资料又很少,真是一个头两个大。好歹最后终于了解了。留个笔记做日后查询。package com.gooddeep.dev.elasticsearch.commons.dao; import
2023-05-31
2024-04-02
2024-04-02
C#数据库查询和操作方法
本篇内容主要讲解“C#数据库查询和操作方法”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C#数据库查询和操作方法”吧!一:C#数据库查询之数据库连接代码:SqlConnectionobjSqlC
2023-06-18
mysql 使用join进行多表关联查询的操作方法
本文介绍了MySQL多表关联查询(JOIN)的操作方法,包括JOIN条件、JOIN类型(INNERJOIN、LEFTJOIN、RIGHTJOIN、FULLJOIN)、JOIN语法和示例。此外,还介绍了高级JOIN选项,如NATURALJOIN、USINGJOIN和CROSSJOIN。最后,提供了优化JOIN查询的建议,如创建索引和选择较小的表作为左表。通过理解这些概念,用户可以创建高效的关联查询,提取有意义的信息并提高应用程序性能。
2024-04-02
在es中查询null值的操作方法
在我们向es中写入数据时,有些时候数据写入到es中的是null,或者没有写入这个字段,那么这个时候在es中该如何查询出这种为null的数据呢,本文给大家详细讲解,需要的朋友参考下吧
2023-02-01
2024-04-02
2024-04-02
2024-04-02
C#如何使用LINQ查询操作符
这篇文章主要讲解了“C#如何使用LINQ查询操作符”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“C#如何使用LINQ查询操作符”吧!连表操作符1、内连接1、使用 join 子句 根据特定的条
2023-07-02
mongodb数据库查询操作方法有哪些
MongoDB数据库的查询操作方法有以下几种:1. find():用于从集合中查找文档。可以通过指定查询条件来筛选文档,并可以使用投影操作符来指定要返回的字段。例:db.collection.find({ age: 25 })2. find
2023-09-04
2024-04-02
2024-04-02
2024-04-02
Mybatis-plus的分页查询操作怎么使用
这篇“Mybatis-plus的分页查询操作怎么使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Mybatis-plus的
2023-07-02
2024-04-02
利用Spring Boot操作MongoDB的方法教程
MongoDBMongoDB作为一种NoSQL数据库产品,其实已经非常著名了。去年,由于MongoDB安全认证的薄弱,上万家公司中招。虽然是一则负面新闻,但是也从侧面说明了MongoDB的流行程度。下图是DB-Engines统计的2017年
2023-05-31
2024-04-02
2024-04-02
2024-04-02