当前位置:   article > 正文

【ES常用查询】基于ElasticsearchRestTemplate及NativeSearchQuery的查询_elasticsearchresttemplate 查询

elasticsearchresttemplate 查询

包含当前es所有的查询,

需要什么代码直接照搬,改个参数就行!

用的好请务必给我点赞!!!感谢爱你们!!!

为啥写这篇文章呢:

大概是因为目前公司用的api跟以前的不太一样,

以前我们是基于高标准客户端直接做的,

但是目前这边同事是基于ElasticsearchRestTemplate跟NativeSearchQuery做的。

  1. import lombok.extern.slf4j.Slf4j;
  2. import org.elasticsearch.common.lucene.search.function.CombineFunction;
  3. import org.elasticsearch.index.query.BoolQueryBuilder;
  4. import org.elasticsearch.index.query.MatchAllQueryBuilder;
  5. import org.elasticsearch.index.query.MatchQueryBuilder;
  6. import org.elasticsearch.index.query.MultiMatchQueryBuilder;
  7. import org.elasticsearch.index.query.QueryBuilders;
  8. import org.elasticsearch.index.query.RangeQueryBuilder;
  9. import org.elasticsearch.index.query.TermsQueryBuilder;
  10. import org.elasticsearch.index.query.WildcardQueryBuilder;
  11. import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
  12. import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
  13. import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
  14. import org.elasticsearch.search.builder.SearchSourceBuilder;
  15. import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
  16. import org.elasticsearch.search.sort.SortBuilder;
  17. import org.elasticsearch.search.sort.SortBuilders;
  18. import org.elasticsearch.search.sort.SortOrder;
  19. import org.springframework.beans.factory.annotation.Autowired;
  20. import org.springframework.data.domain.PageRequest;
  21. import org.springframework.data.domain.Pageable;
  22. import org.springframework.data.domain.Sort;
  23. import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
  24. import org.springframework.data.elasticsearch.core.SearchHit;
  25. import org.springframework.data.elasticsearch.core.SearchHits;
  26. import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
  27. import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
  28. import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
  29. import org.springframework.web.bind.annotation.PostMapping;
  30. import org.springframework.web.bind.annotation.RequestMapping;
  31. import org.springframework.web.bind.annotation.RestController;
  32. import java.util.List;
  33. import java.util.Map;
  34. @Slf4j
  35. @RestController
  36. @RequestMapping("/v/k/t/query")
  37. public class EsTestController {
  38. //聚合2
  39. //参加聚合的字段必须是keyword、日期、数值、布尔类型
  40. @PostMapping("/es/agg2")
  41. public void agg2() throws IOException {
  42. // 1.创建Request对象
  43. SearchRequest request = new SearchRequest("298_ops-web-js_1");
  44. // 2.准备请求的参数:DSL语句
  45. request.source().size(0);
  46. //参数一:聚合查询的名字 参数二:根据appid做分组 参数三:最多显示10
  47. // TermsAggregationBuilder aggregationBuilder = AggregationBuilders.max("bsVersionAgg").field("appId");
  48. MaxAggregationBuilder maxAggs = AggregationBuilders.max("score").field("bsVersion");
  49. request.source().aggregation(
  50. maxAggs
  51. );
  52. try {
  53. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  54. Aggregations aggregations = response.getAggregations();
  55. Terms bsVersionAgg = aggregations.get("bsVersionAgg");
  56. List<? extends Terms.Bucket> buckets = bsVersionAgg.getBuckets();
  57. for (Terms.Bucket bucket : buckets) {
  58. String key = bucket.getKeyAsString();
  59. //getDocCount:该桶下的文档总数
  60. long docCount = bucket.getDocCount();
  61. log.info("key:{},docCount:{}", key, docCount);
  62. }
  63. } catch (IOException e) {
  64. log.error("es查询异常:{}", e.getMessage());
  65. }
  66. }
  67. //聚合
  68. //参加聚合的字段必须是keyword、日期、数值、布尔类型
  69. @PostMapping("/es/agg")
  70. public void agg() {
  71. // 1.创建Request对象
  72. SearchRequest request = new SearchRequest("298_ops-web-js_1");
  73. // 2.准备请求的参数:DSL语句
  74. request.source().size(0);
  75. //参数一:聚合查询的名字 参数二:根据appid做分组 参数三:最多显示10
  76. TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("bsVersionAgg").field("appId").size(5);
  77. request.source().aggregation(
  78. aggregationBuilder
  79. );
  80. try {
  81. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  82. Aggregations aggregations = response.getAggregations();
  83. Terms bsVersionAgg = aggregations.get("bsVersionAgg");
  84. List<? extends Terms.Bucket> buckets = bsVersionAgg.getBuckets();
  85. for (Terms.Bucket bucket : buckets) {
  86. String key = bucket.getKeyAsString();
  87. //getDocCount:该桶下的文档总数
  88. long docCount = bucket.getDocCount();
  89. log.info("key:{},docCount:{}", key, docCount);
  90. }
  91. } catch (IOException e) {
  92. log.error("es查询异常:{}", e.getMessage());
  93. }
  94. }
  95. /************************************************************************
  96. ————————————————————————————以下为不携带聚合的查询————————————————————————————————————————————
  97. ************************************************************************/
  98. /**
  99. * 测试es各种查询方法*
  100. */
  101. @Autowired
  102. ElasticsearchRestTemplate elasticsearchRestTemplate;
  103. //通配符查询
  104. @PostMapping("/es/wildcard")
  105. public void wildcard() {
  106. //*:匹配任意数量的字符(包括零个字符)。 *x*: 对x做前后N位做模糊查询,前后有多少值都可以查到(也可以左模糊或者右模糊)
  107. //?:用于匹配单个字符. user?a: user?a 匹配user1a,但不匹配user123a
  108. //^:必须以某个字符开头,如^user*:必须以user开头
  109. //$:必须以某个字符结尾,如user$:必须以user结尾
  110. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  111. //wildcardQuery:通配符查询
  112. WildcardQueryBuilder bsVersion = QueryBuilders.wildcardQuery("bsVersion", "*1*");
  113. WildcardQueryBuilder bsVersion2 = QueryBuilders.wildcardQuery("type", "*j*");
  114. boolQueryBuilder.must(bsVersion).should(bsVersion2);
  115. NativeSearchQuery dsl = new NativeSearchQueryBuilder()
  116. }
  117. //高亮
  118. //默认情况下:只能对查询字段高亮!!!
  119. //加了.requireFieldMatch(false) 可以对非查询字段高亮,具体看下文
  120. @PostMapping("/es/highlight")
  121. public void highlight() {
  122. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  123. //wildcardQuery:通配符查询
  124. WildcardQueryBuilder bsVersion = QueryBuilders.wildcardQuery("bsVersion", "*1*");
  125. WildcardQueryBuilder bsVersion2 = QueryBuilders.wildcardQuery("type", "*j*");
  126. boolQueryBuilder.must(bsVersion).should(bsVersion2);
  127. NativeSearchQuery dsl = new NativeSearchQueryBuilder()
  128. .withQuery(boolQueryBuilder)
  129. .withHighlightFields(
  130. //.requireFieldMatch(false) : 加了可以对非查询字段高亮
  131. new HighlightBuilder.Field("bsVersion").preTags("<em>").postTags("</em>").requireFieldMatch(false),
  132. new HighlightBuilder.Field("provinceNameCn").preTags("<em>").postTags("</em>").requireFieldMatch(false),
  133. new HighlightBuilder.Field("isp").preTags("<em>").postTags("</em>").requireFieldMatch(false),
  134. new HighlightBuilder.Field("type").preTags("<em>").postTags("</em>").requireFieldMatch(false),
  135. new HighlightBuilder.Field("agentId").preTags("<em>").postTags("</em>").requireFieldMatch(false)
  136. )
  137. .build();
  138. SearchHits<Map> search = elasticsearchRestTemplate.search(dsl, Map.class, IndexCoordinates.of("298_ops-web-js_1"));
  139. log.info("总条数:{}", search.getTotalHits());
  140. for (SearchHit<Map> searchHit : search.getSearchHits()) {
  141. // 高亮字段是个大MAP 高亮字段集合 = {bsVersion=[<em>115</em>]} //K=字段名 V=高亮了的数据集合
  142. Map<String, List<String>> highlightFields = searchHit.getHighlightFields();
  143. System.out.println("获取高亮字段集合:bsVersion = " + highlightFields.get("bsVersion"));
  144. System.out.println("获取高亮字段集合:provinceNameCn = " + highlightFields.get("provinceNameCn"));
  145. System.out.println("获取高亮字段集合:isp = " + highlightFields.get("isp"));
  146. System.out.println("获取高亮字段集合:type = " + highlightFields.get("type"));
  147. System.out.println("获取高亮字段集合:agentId = " + highlightFields.get("agentId"));
  148. List<String> bsVersionResult = highlightFields.get("bsVersion");
  149. for (String s : bsVersionResult) {
  150. System.out.println("bsVersion集合每一个值为 = " + s);
  151. }
  152. // highlightFields.forEach((k, v) -> {
  153. // //获取高亮字段:k = bsVersion v = [<em>115</em>]
  154. // System.out.println("获取高亮字段:k = " + k + " v = " + v);
  155. // });
  156. }
  157. log.info("总条数:{}", search.getTotalHits());
  158. System.out.println("search.getSearchHits().size() = " + search.getSearchHits().size());
  159. }
  160. //排序
  161. @PostMapping("/es/sort")
  162. public void sort() {
  163. MatchAllQueryBuilder matchAllQuery = QueryBuilders.matchAllQuery();
  164. //备注:这里用的是NativeSearchQueryBuilder:xxxBuilder。最后一定要.build();,不然条件用不了
  165. NativeSearchQuery dsl = new NativeSearchQueryBuilder()
  166. .withQuery(matchAllQuery)
  167. //备注:应该是要keyword,paasword这一类才能排序。我用text类型排序报:非法字段异常
  168. .withSorts(SortBuilders.fieldSort("appId").order(SortOrder.ASC)) //排序:根据bsVersion升序排序
  169. .build();
  170. SearchHits<Map> search = elasticsearchRestTemplate.search(dsl, Map.class, IndexCoordinates.of("298_ops-web-js_1"));
  171. log.info("总条数:{}", search.getTotalHits());
  172. for (SearchHit<Map> searchHit : search.getSearchHits()) {
  173. System.out.println("单条文档的原数据 = " + searchHit.getContent());
  174. System.out.println("单条文档的id = " + searchHit.getId());
  175. System.out.println("单条文档的评分 = " + searchHit.getScore());
  176. System.out.println("单条文档索引名(表名) = " + searchHit.getIndex());//298_ops-web-js_1就是你输入的索引库名
  177. }
  178. }
  179. //分页
  180. @PostMapping("/es/page")
  181. public void page() {
  182. Integer page = 1;
  183. Integer size = 10;
  184. MatchAllQueryBuilder matchAllQuery = QueryBuilders.matchAllQuery();
  185. NativeSearchQuery dsl = new NativeSearchQuery(matchAllQuery);
  186. //分页
  187. Pageable pageable = PageRequest.of((page - 1) * size, size);
  188. dsl.setPageable(pageable);
  189. SearchHits<Map> search = elasticsearchRestTemplate.search(dsl, Map.class, IndexCoordinates.of("298_ops-web-js_1"));
  190. log.info("总条数:{}", search.getTotalHits());
  191. // 获取当前页数
  192. log.info("当前页数:{}", page);
  193. // 获取当前页的条数
  194. int currentSize = search.getSearchHits().size();
  195. log.info("当前页条数:{}", currentSize);
  196. //数据列表:search.getSearchHits() for出每一条,然后加到list中
  197. for (SearchHit<Map> searchHit : search.getSearchHits()) {
  198. System.out.println("单条文档的原数据 = " + searchHit.getContent());
  199. System.out.println("单条文档的id = " + searchHit.getId());
  200. System.out.println("单条文档的评分 = " + searchHit.getScore());
  201. System.out.println("单条文档索引名(表名) = " + searchHit.getIndex());//298_ops-web-js_1就是你输入的索引库名
  202. }
  203. }
  204. //布尔查询
  205. @PostMapping("/es/boolQueryBuilder")
  206. public void boolQueryBuilder() {
  207. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  208. //must 必须满足且参与算分
  209. boolQueryBuilder.must(QueryBuilders.matchQuery("bsVersion", "114"));
  210. //mustNot 必须不满足 appID 300-700之间不参与查询(就是直接筛掉了)
  211. boolQueryBuilder.mustNot(QueryBuilders.rangeQuery("appId").gte("300").lte("700"));
  212. //filter 必须满足,且不参与算分
  213. // boolQueryBuilder.filter(QueryBuilders.termQuery("agentId", "298_ead348abbaf30f48"));
  214. NativeSearchQuery dsl = new NativeSearchQuery(boolQueryBuilder);
  215. SearchHits<Map> search = elasticsearchRestTemplate.search(dsl, Map.class, IndexCoordinates.of("298_ops-web-js_1"));
  216. log.info("总条数:{}", search.getTotalHits());
  217. for (SearchHit<Map> searchHit : search.getSearchHits()) {
  218. System.out.println("单条文档的原数据 = " + searchHit.getContent());
  219. System.out.println("单条文档的id = " + searchHit.getId());
  220. System.out.println("单条文档的评分 = " + searchHit.getScore());
  221. System.out.println("单条文档索引名(表名) = " + searchHit.getIndex());//298_ops-web-js_1就是你输入的索引库名
  222. }
  223. }
  224. //算分函数查询
  225. @PostMapping("/es/FunctionScoreQueryBuilder")
  226. public void FunctionScoreQueryBuilder() {
  227. FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
  228. //原始查询
  229. QueryBuilders.matchAllQuery(),
  230. //算分数组
  231. new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
  232. //第一个元素
  233. new FunctionScoreQueryBuilder.FilterFunctionBuilder(
  234. //过滤器
  235. QueryBuilders.matchQuery("bsVersion", "114"),
  236. //权重
  237. ScoreFunctionBuilders.weightFactorFunction(10)
  238. ),
  239. //第二个元素
  240. new FunctionScoreQueryBuilder.FilterFunctionBuilder(
  241. //过滤器
  242. QueryBuilders.matchQuery("bsVersion", "115"),
  243. //权重
  244. ScoreFunctionBuilders.weightFactorFunction(10)
  245. )
  246. }).boostMode(CombineFunction.REPLACE);
  247. NativeSearchQuery dsl = new NativeSearchQuery(functionScoreQueryBuilder);
  248. SearchHits<Map> search = elasticsearchRestTemplate.search(dsl, Map.class, IndexCoordinates.of("298_ops-web-js_1"));
  249. log.info("总条数:{}", search.getTotalHits());
  250. for (SearchHit<Map> searchHit : search.getSearchHits()) {
  251. System.out.println("单条文档的原数据 = " + searchHit.getContent());
  252. System.out.println("单条文档的id = " + searchHit.getId());
  253. System.out.println("单条文档的评分 = " + searchHit.getScore());
  254. System.out.println("单条文档索引名(表名) = " + searchHit.getIndex());//298_ops-web-js_1就是你输入的索引库名
  255. }
  256. }
  257. //范围查询
  258. @PostMapping("/es/rangeQuery")
  259. public void rangeQuery() {
  260. //范围查询 appId字段 >=0 <=200 的数据
  261. RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("appId").gte("0").lte("200");
  262. NativeSearchQuery dsl = new NativeSearchQuery(rangeQueryBuilder);
  263. SearchHits<Map> search = elasticsearchRestTemplate.search(dsl, Map.class, IndexCoordinates.of("298_ops-web-js_1"));
  264. log.info("总条数:{}", search.getTotalHits());
  265. for (SearchHit<Map> searchHit : search.getSearchHits()) {
  266. System.out.println("单条文档的原数据 = " + searchHit.getContent());
  267. System.out.println("单条文档的id = " + searchHit.getId());
  268. System.out.println("单条文档的评分 = " + searchHit.getScore());
  269. System.out.println("单条文档索引名(表名) = " + searchHit.getIndex());//298_ops-web-js_1就是你输入的索引库名
  270. }
  271. }
  272. //精确查询
  273. @PostMapping("/es/termQuery")
  274. public void termQuery() {
  275. //根据isp字段 精确查询 内网IP
  276. TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("isp", " 内网IP ");
  277. NativeSearchQuery dsl = new NativeSearchQuery(termsQueryBuilder);
  278. SearchHits<Map> search = elasticsearchRestTemplate.search(dsl, Map.class, IndexCoordinates.of("298_ops-web-js_1"));
  279. log.info("总条数:{}", search.getTotalHits());
  280. for (SearchHit<Map> searchHit : search.getSearchHits()) {
  281. System.out.println("单条文档的原数据 = " + searchHit.getContent());
  282. System.out.println("单条文档的id = " + searchHit.getId());
  283. System.out.println("单条文档的评分 = " + searchHit.getScore());
  284. System.out.println("单条文档索引名(表名) = " + searchHit.getIndex());//298_ops-web-js_1就是你输入的索引库名
  285. }
  286. }
  287. //多字段查询
  288. @PostMapping("/es/multiMatchQuery")
  289. public void multiMatchQuery() {
  290. //备注:字段必须是text类型,可以分词类型!!!!
  291. //查找keyword、数值、日期、boolean等会报错!!!
  292. //如果放入精确类型的字段,会报错!!!!
  293. MultiMatchQueryBuilder multiMatchQuery = QueryBuilders.multiMatchQuery("114", "bsVersion", "type");//查询114根据"bsVersion","type"
  294. NativeSearchQuery dsl = new NativeSearchQuery(multiMatchQuery);
  295. SearchHits<Map> search = elasticsearchRestTemplate.search(dsl, Map.class, IndexCoordinates.of("298_ops-web-js_1"));
  296. log.info("总条数:{}", search.getTotalHits());
  297. for (SearchHit<Map> searchHit : search.getSearchHits()) {
  298. System.out.println("单条文档的原数据 = " + searchHit.getContent());
  299. System.out.println("单条文档的id = " + searchHit.getId());
  300. System.out.println("单条文档的评分 = " + searchHit.getScore());
  301. System.out.println("单条文档索引名(表名) = " + searchHit.getIndex());//298_ops-web-js_1就是你输入的索引库名
  302. }
  303. }
  304. //单字段查询
  305. @PostMapping("/es/matchQuery")
  306. public void matchQuery() {
  307. MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("bsVersion", "114");
  308. NativeSearchQuery dsl = new NativeSearchQuery(matchQuery);
  309. SearchHits<Map> search = elasticsearchRestTemplate.search(dsl, Map.class, IndexCoordinates.of("298_ops-web-js_1"));
  310. log.info("总条数:{}", search.getTotalHits());
  311. for (SearchHit<Map> searchHit : search.getSearchHits()) {
  312. System.out.println("单条文档的原数据 = " + searchHit.getContent());
  313. System.out.println("单条文档的id = " + searchHit.getId());
  314. System.out.println("单条文档的评分 = " + searchHit.getScore());
  315. System.out.println("单条文档索引名(表名) = " + searchHit.getIndex());//298_ops-web-js_1就是你输入的索引库名
  316. }
  317. }
  318. //查询所有
  319. @PostMapping("/es/matchAllQuery")
  320. public void matchAllQuery() {
  321. MatchAllQueryBuilder matchAllQuery = QueryBuilders.matchAllQuery();
  322. NativeSearchQuery dsl = new NativeSearchQuery(matchAllQuery);
  323. SearchHits<Map> search = elasticsearchRestTemplate.search(dsl, Map.class, IndexCoordinates.of("298_ops-web-js_1"));
  324. log.info("总条数:{}", search.getTotalHits());
  325. log.info("查询原始对象:{}", search.getSearchHits());
  326. log.info("分数值:{}", search.getMaxScore());
  327. log.info("有无聚合:{}", search.hasAggregations());
  328. log.info("返回搜索命中数量的关系,例如精确值、估计值:{}", search.getTotalHitsRelation());
  329. log.info("判断是否存在搜索命中结果:{}", search.hasSearchHits());
  330. //原始结果的每一条数据
  331. for (SearchHit<Map> searchHit : search.getSearchHits()) {
  332. System.out.println("单条文档 = " + searchHit);
  333. System.out.println("单条文档的原数据 = " + searchHit.getContent());
  334. }
  335. }
  336. }

————————————————————————————————————

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/576796
推荐阅读
相关标签
  

闽ICP备14008679号