ElasticSearch学习笔记(九)Java AP实现搜索,排序,高亮,分页

港控/mmm° 2022-06-11 05:17 386阅读 0赞

虽然上一篇中的对索引的搜索可以在一定程度上获取索引的信息,但是毕竟功能是有限的,本篇主要是对elasticsearch使用javaAPI实现搜索功能的笔记。

一、搜索

  1. package test;
  2. import static org.elasticsearch.index.query.QueryBuilders.termQuery;
  3. import java.net.InetAddress;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. import org.apache.lucene.index.Terms;
  7. import org.elasticsearch.action.search.MultiSearchResponse;
  8. import org.elasticsearch.action.search.SearchRequest;
  9. import org.elasticsearch.action.search.SearchRequestBuilder;
  10. import org.elasticsearch.action.search.SearchResponse;
  11. import org.elasticsearch.client.transport.TransportClient;
  12. import org.elasticsearch.common.settings.Settings;
  13. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  14. import org.elasticsearch.common.unit.TimeValue;
  15. import org.elasticsearch.index.query.QueryBuilder;
  16. import org.elasticsearch.index.query.QueryBuilders;
  17. import org.elasticsearch.script.ScriptType;
  18. import org.elasticsearch.script.mustache.SearchTemplateRequestBuilder;
  19. import org.elasticsearch.search.SearchHit;
  20. import org.elasticsearch.search.aggregations.AggregationBuilders;
  21. import org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval;
  22. import org.elasticsearch.search.sort.FieldSortBuilder;
  23. import org.elasticsearch.search.sort.SortOrder;
  24. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  25. @SuppressWarnings({ "resource","deprecation" })
  26. public class testSearch {
  27. public static void main(String[] args) throws Exception{
  28. searchmethod6();
  29. }
  30. /** * 方法一 * @throws Exception */
  31. public static void searchmethod1() throws Exception{
  32. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
  33. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));
  34. SearchResponse response = client.prepareSearch("movies").setTypes("movie").get();
  35. println(response);
  36. for (SearchHit searchHit: response.getHits()) {
  37. println(searchHit);
  38. }
  39. }
  40. /** * 方法二 * @throws Exception */
  41. public static void searchmethod2() throws Exception{
  42. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
  43. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));
  44. QueryBuilder qb1 = termQuery("user","10");
  45. // QueryBuilder qb2 = QueryBuilders.multiMatchQuery("git", "title", "content");
  46. SearchResponse response = client.prepareSearch("movies").setQuery(qb1).get();
  47. for (SearchHit searchHit: response.getHits()) {
  48. println(searchHit);
  49. }
  50. }
  51. /** * 方法三 * @throws Exception * 这个相当于之前的分页,使用的是Scroll方法 */
  52. public static void searchmethod3() throws Exception{
  53. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
  54. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));
  55. QueryBuilder qb = termQuery("user", "kimchy");
  56. SearchResponse scrollResp = client.prepareSearch("movies")
  57. .addSort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC)
  58. .setScroll(new TimeValue(60000))
  59. .setQuery(qb)
  60. .setSize(1).get();
  61. do {
  62. for (SearchHit hit : scrollResp.getHits().getHits()) {
  63. println(hit);
  64. }
  65. scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
  66. } while(scrollResp.getHits().getHits().length != 0);
  67. }
  68. /** * 方法四 * @throws Exception */
  69. public static void searchmethod4() throws Exception{
  70. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
  71. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));
  72. SearchRequestBuilder srb1 = client.prepareSearch().setQuery(QueryBuilders.queryStringQuery("kimchy"));
  73. SearchRequestBuilder srb2 = client.prepareSearch().setQuery(QueryBuilders.matchQuery("user", "kimchy"));
  74. MultiSearchResponse sr = client.prepareMultiSearch().add(srb1).add(srb2).get();
  75. for (MultiSearchResponse.Item item : sr.getResponses()) {
  76. SearchResponse response = item.getResponse();
  77. for (SearchHit searchHit : response.getHits()) {
  78. println(searchHit);
  79. }
  80. }
  81. }
  82. /** * 方法五 * 这个方法先欠着,不是很懂 * @throws Exception */
  83. public static void searchmethod5() throws Exception{
  84. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
  85. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));
  86. SearchResponse sr = client.prepareSearch()
  87. .setQuery(QueryBuilders.matchAllQuery())
  88. .addAggregation(
  89. AggregationBuilders.terms("agg1").field("field")
  90. )
  91. .addAggregation(
  92. AggregationBuilders.dateHistogram("agg2")
  93. .field("birth")
  94. .dateHistogramInterval(DateHistogramInterval.YEAR)
  95. )
  96. .get();
  97. // Get your facet results
  98. Terms agg1 = sr.getAggregations().get("agg1");
  99. // DateHistogram agg2 = sr.getAggregations().get("agg2");
  100. }
  101. /** * 方法六 * 能运行,但是就是不知道为什么查询不到结果,同时感觉这种方法很鸡肋,感觉写起来很麻烦,顺便说一下这个东西好像也可以在script下配置,我测试失败,但是感觉没什么用,就不深究了。 * https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-search-template.html * @throws Exception */
  102. public static void searchmethod6() throws Exception{
  103. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
  104. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));
  105. Map<String, Object> json = new HashMap<>();
  106. json.put("param_gender", "1962");
  107. SearchResponse response = new SearchTemplateRequestBuilder(client)
  108. .setScript("{\n" +
  109. " \"query\" : {\n" +
  110. " \"match\" : {\n" +
  111. " \"year\" : \"{ {param_gender}}\"\n" +
  112. " }\n" +
  113. " }\n" +
  114. "}")
  115. .setScriptType(ScriptType.INLINE)
  116. .setScriptParams(json)
  117. .setRequest(new SearchRequest())
  118. .get()
  119. .getResponse();
  120. println(response);
  121. System.out.println(response.getHits().getTotalHits());
  122. for (SearchHit searchHit : response.getHits()) {
  123. println(searchHit);
  124. }
  125. }
  126. /** * 输出结果SearchResponse * @param response */
  127. public static void println(SearchResponse response){
  128. System.err.println("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
  129. System.err.println(
  130. "getFailedShards : " + response.getFailedShards() + "\n" +
  131. "getNumReducePhases : " + response.getNumReducePhases() + "\n" +
  132. "getScrollId : " + response.getScrollId() + "\n" +
  133. "getTookInMillis : " + response.getTookInMillis() + "\n" +
  134. "getTotalShards : " + response.getTotalShards() + "\n" +
  135. "getAggregations : " + response.getAggregations() + "\n" +
  136. "getProfileResults : " + response.getProfileResults() + "\n" +
  137. "getShardFailures : " + response.getShardFailures() + "\n" +
  138. "getSuggest : " + response.getSuggest() + "\n" +
  139. "getTook : " + response.getTook() + "\n" +
  140. "isTerminatedEarly : " + response.isTerminatedEarly() + "\n" +
  141. "isTimedOut : " + response.isTimedOut() + "\n" +
  142. "remoteAddress : " + response.remoteAddress() + "\n" +
  143. "status : " + response.status() + "\n" +
  144. "getHits : " + response.getHits()
  145. );
  146. }
  147. /** * 输出结果SearchResponse * @param response */
  148. public static void println(SearchHit searchHit){
  149. System.err.println("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
  150. System.err.println(
  151. "docId : " + searchHit.docId() + "\n" +
  152. "getId : " + searchHit.getId() + "\n" +
  153. "getIndex : " + searchHit.getIndex()+ "\n" +
  154. "getScore : " + searchHit.getScore() + "\n" +
  155. "getSourceAsString : " + searchHit.getSourceAsString() + "\n" +
  156. "getType : " + searchHit.getType() + "\n" +
  157. "getVersion : " + searchHit.getVersion() + "\n" +
  158. "fieldsOrNull : " + searchHit.fieldsOrNull() + "\n" +
  159. "getExplanation : " + searchHit.getExplanation() + "\n" +
  160. "getFields : " + searchHit.getFields() + "\n" +
  161. "highlightFields : " + searchHit.highlightFields() + "\n" +
  162. "hasSource : " + searchHit.hasSource()
  163. );
  164. }
  165. }

二、DSL搜索

DSL就是实现类似schema发出的请求一样的,这方面的介绍主要是在https://www.elastic.co/guide/en/elasticsearch/reference/5.5/getting-started.html和http://www.yiibai.com/elasticsearch/elasticsearch_index_apis.html这两个地方,但是由于这里面的API是真的多,这里就介绍一部分,还有很多东西,可以有需要的时候去官网https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-query-dsl.html看看。

  1. package test;
  2. import static org.elasticsearch.index.query.QueryBuilders.*;
  3. import java.net.InetAddress;
  4. import org.elasticsearch.action.search.SearchResponse;
  5. import org.elasticsearch.client.transport.TransportClient;
  6. import org.elasticsearch.common.settings.Settings;
  7. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  8. import org.elasticsearch.index.query.QueryBuilder;
  9. import org.elasticsearch.search.SearchHit;
  10. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  11. @SuppressWarnings({
  12. "resource","deprecation"})
  13. public class testDSL {
  14. static TransportClient client;
  15. //https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-query-dsl.html
  16. public static void main(String[] args) throws Exception {
  17. client = new PreBuiltTransportClient(Settings.EMPTY)
  18. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));
  19. // _matchAllQuery();
  20. /** * 从这往下是全文检索的 */
  21. // _matchQuery();
  22. // _multiMatchQuery();
  23. // _commonTermsQuery();
  24. // _queryStringQuery();
  25. // _simpleQueryStringQuery();
  26. /** * 从这往下主要运营与数字、日期、枚举等类型的检索 */
  27. // _termQuery();
  28. // _termsQuery();
  29. // _rangeQuery();
  30. // _existsQuery();
  31. // _prefixQuery();
  32. // _wildcardQuery();
  33. // _fuzzyQuery();
  34. // _typeQuery();
  35. _idsQuery();
  36. }
  37. /** * 方法一:获取所有 * @throws Exception */
  38. public static void _matchAllQuery() throws Exception{
  39. QueryBuilder qb = matchAllQuery();
  40. dealQueryBuilder(qb);
  41. }
  42. /** * 方法二:指定单查询条件 * @throws Exception */
  43. public static void _matchQuery() throws Exception{
  44. QueryBuilder qb = matchQuery(
  45. "user" ,
  46. "kimchy"
  47. );
  48. dealQueryBuilder(qb);
  49. }
  50. /** * 方法三:指定多查询条件 * @throws Exception */
  51. public static void _multiMatchQuery() throws Exception{
  52. QueryBuilder qb = multiMatchQuery(
  53. "kimchy elasticsearch",
  54. "user", "message"
  55. );
  56. dealQueryBuilder(qb);
  57. }
  58. /** * 方法四:感觉和方法二_matchQuery一样,不知道差别 * @throws Exception */
  59. public static void _commonTermsQuery() throws Exception{
  60. QueryBuilder qb = commonTermsQuery("user",
  61. "kimchy");
  62. dealQueryBuilder(qb);
  63. }
  64. /** * 方法五:+包含 -除外,但是这个查询没有结果,很奇怪 * @throws Exception */
  65. public static void _queryStringQuery() throws Exception{
  66. QueryBuilder qb = queryStringQuery("+kimchy -elasticsearch");
  67. dealQueryBuilder(qb);
  68. }
  69. /** * 方法六:+包含 -除外 * @throws Exception */
  70. public static void _simpleQueryStringQuery() throws Exception{
  71. QueryBuilder qb = simpleQueryStringQuery("+kimchy -elasticsearch");
  72. dealQueryBuilder(qb);
  73. }
  74. //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
  75. /** * 方法七_:termQuery * @throws Exception */
  76. public static void _termQuery() throws Exception{
  77. QueryBuilder qb = termQuery(
  78. "user",
  79. "kimchy"
  80. );
  81. dealQueryBuilder(qb);
  82. }
  83. /** * 方法八:_termsQuery * @throws Exception */
  84. public static void _termsQuery() throws Exception{
  85. QueryBuilder qb = termsQuery("tags",
  86. "blue", "pill");
  87. dealQueryBuilder(qb);
  88. }
  89. /** * 方法九:_rangeQuery * @throws Exception */
  90. public static void _rangeQuery() throws Exception{
  91. QueryBuilder qb = rangeQuery("price")
  92. .from(5)
  93. .to(10)
  94. .includeLower(true)
  95. .includeUpper(false);
  96. // A simplified form using gte, gt, lt or lte
  97. QueryBuilder _qb = rangeQuery("age")
  98. .gte("10")
  99. .lt("20");
  100. dealQueryBuilder(qb);
  101. }
  102. /** * 方法十:_existsQuery * 匹配含有user字段的记录 * @throws Exception */
  103. public static void _existsQuery() throws Exception{
  104. QueryBuilder qb = existsQuery("user");
  105. dealQueryBuilder(qb);
  106. }
  107. /** * 方法十一:_prefixQuery * 匹配user中前缀为fds的记录 * @throws Exception */
  108. public static void _prefixQuery() throws Exception{
  109. QueryBuilder qb = prefixQuery(
  110. "user",
  111. "fds"
  112. );
  113. dealQueryBuilder(qb);
  114. }
  115. /** * 方法十二:_wildcardQuery * 通配符 * @throws Exception */
  116. public static void _wildcardQuery() throws Exception{
  117. QueryBuilder qb = wildcardQuery("user", "k?mc*");
  118. dealQueryBuilder(qb);
  119. }
  120. /** * 方法十三:_fuzzyQuery * @throws Exception */
  121. public static void _fuzzyQuery() throws Exception{
  122. QueryBuilder qb = fuzzyQuery(
  123. "user",
  124. "kimzhy"
  125. );
  126. dealQueryBuilder(qb);
  127. }
  128. /** * 方法十四:_typeQuery * @throws Exception */
  129. public static void _typeQuery() throws Exception{
  130. QueryBuilder qb = typeQuery("movie");
  131. dealQueryBuilder(qb);
  132. }
  133. /** * 方法十五:_idsQuery * 类型是可选的 * @throws Exception */
  134. public static void _idsQuery() throws Exception{
  135. QueryBuilder qb = idsQuery("movie")
  136. .addIds("1", "4", "100");
  137. dealQueryBuilder(qb);
  138. }
  139. /** * 这部分代码的复用性太高了,抽离出来。 * @param qb */
  140. public static void dealQueryBuilder(QueryBuilder qb){
  141. SearchResponse response = client.prepareSearch("movies").setQuery(qb).get();
  142. for (SearchHit searchHit : response.getHits()) {
  143. println(searchHit);
  144. }
  145. }
  146. /** * 输出结果SearchResponse * @param response */
  147. public static void println(SearchHit searchHit){
  148. System.err.println("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
  149. System.err.println(
  150. "docId : " + searchHit.docId() + "\n" +
  151. "getId : " + searchHit.getId() + "\n" +
  152. "getIndex : " + searchHit.getIndex()+ "\n" +
  153. "getScore : " + searchHit.getScore() + "\n" +
  154. "getSourceAsString : " + searchHit.getSourceAsString() + "\n" +
  155. "getType : " + searchHit.getType() + "\n" +
  156. "getVersion : " + searchHit.getVersion() + "\n" +
  157. "fieldsOrNull : " + searchHit.fieldsOrNull() + "\n" +
  158. "getExplanation : " + searchHit.getExplanation() + "\n" +
  159. "getFields : " + searchHit.getFields() + "\n" +
  160. "highlightFields : " + searchHit.highlightFields() + "\n" +
  161. "hasSource : " + searchHit.hasSource()
  162. );
  163. }
  164. }

三、分词、排序、高亮

  1. package test;
  2. import java.net.InetAddress;
  3. import org.elasticsearch.action.search.SearchResponse;
  4. import org.elasticsearch.client.transport.TransportClient;
  5. import org.elasticsearch.common.settings.Settings;
  6. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  7. import org.elasticsearch.index.query.QueryBuilder;
  8. import org.elasticsearch.index.query.QueryBuilders;
  9. import org.elasticsearch.search.SearchHit;
  10. import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
  11. import org.elasticsearch.search.sort.FieldSortBuilder;
  12. import org.elasticsearch.search.sort.SortBuilder;
  13. import org.elasticsearch.search.sort.SortBuilders;
  14. import org.elasticsearch.search.sort.SortOrder;
  15. import org.elasticsearch.transport.client.PreBuiltTransportClient;
  16. @SuppressWarnings({ "resource", "deprecation" })
  17. public class testUtil {
  18. public static void main(String[] args) throws Exception {
  19. // fenye();
  20. sort();
  21. // highlighter();
  22. }
  23. /** * 分页 * @throws Exception */
  24. public static void fenye() throws Exception {
  25. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
  26. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));
  27. SearchResponse response = client.prepareSearch("movies")
  28. .setQuery(QueryBuilders.matchAllQuery())
  29. .setFrom(10)
  30. .setSize(20)
  31. .execute().actionGet();
  32. for (SearchHit searchHit : response.getHits()) {
  33. println(searchHit);
  34. }
  35. }
  36. /** * 排序 * @throws Exception */
  37. public static void sort() throws Exception {
  38. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
  39. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));
  40. SearchResponse response = client.prepareSearch("movies")
  41. .setQuery(QueryBuilders.matchAllQuery())
  42. .addSort("postDate", SortOrder.ASC)
  43. .execute().actionGet();
  44. for (SearchHit searchHit : response.getHits()) {
  45. println(searchHit);
  46. }
  47. }
  48. /** * 高亮 * @throws Exception */
  49. public static void highlighter() throws Exception{
  50. TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
  51. .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("106.14.112.215"), 9300));
  52. QueryBuilder matchQuery = QueryBuilders.matchQuery("user", "kimchy");
  53. HighlightBuilder hiBuilder=new HighlightBuilder();
  54. hiBuilder.preTags("<h2>");
  55. hiBuilder.postTags("</h2>");
  56. hiBuilder.field("user");
  57. // 搜索数据
  58. SearchResponse response = client.prepareSearch("movies")
  59. .setQuery(matchQuery)
  60. .highlighter(hiBuilder)
  61. .execute().actionGet();
  62. for (SearchHit searchHit : response.getHits()) {
  63. println(searchHit);
  64. }
  65. }
  66. /** * 输出结果SearchResponse * @param response */
  67. public static void println(SearchHit searchHit){
  68. System.err.println("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-");
  69. System.err.println(
  70. "docId : " + searchHit.docId() + "\n" +
  71. "getId : " + searchHit.getId() + "\n" +
  72. "getIndex : " + searchHit.getIndex()+ "\n" +
  73. "getScore : " + searchHit.getScore() + "\n" +
  74. "getSourceAsString : " + searchHit.getSourceAsString() + "\n" +
  75. "getType : " + searchHit.getType() + "\n" +
  76. "getVersion : " + searchHit.getVersion() + "\n" +
  77. "fieldsOrNull : " + searchHit.fieldsOrNull() + "\n" +
  78. "getExplanation : " + searchHit.getExplanation() + "\n" +
  79. "getFields : " + searchHit.getFields() + "\n" +
  80. "highlightFields : " + searchHit.highlightFields() + "\n" +
  81. "hasSource : " + searchHit.hasSource()
  82. );
  83. }
  84. }

源码我放在http://download.csdn.net/detail/q15150676766/9920331这里了,有需要的可以去下载看看

发表评论

表情:
评论列表 (有 0 条评论,386人围观)

还没有评论,来说两句吧...

相关阅读