全文检索:

两种查询:
1,macth
2,multi_match (多字段查询)查询与match_all的API基本一致
都是属于query的部分
而两种查询的
差异在于类型和条件上。
请求方式一样路径一样

全文查询 match 和multi_match 查询与match_all的API基本一致
差别是查询条件 也就是query、的部分

image.png

image.png

精确查询:

term查询和range查询 同样利用QueryBuilders实现:
image.png

符合查询—boolean query

image.png

  1. @SpringBootTest
  2. class HotelSearchTest {
  3. //l利用service来完成增删改查
  4. @Autowired
  5. private IHotelService hotelService;
  6. private RestHighLevelClient client;
  7. @Test
  8. void testMatchAll() throws IOException {
  9. //准备request对象
  10. SearchRequest request = new SearchRequest("hotel");
  11. //准备DSL
  12. request.source().query(QueryBuilders.matchAllQuery());
  13. //发送请求
  14. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  15. AllMatch(response);
  16. }
  17. @Test
  18. void testmatch() throws IOException {
  19. //准备REQUEST
  20. SearchRequest request = new SearchRequest("hotel");
  21. //准备DSL
  22. request.source().query(QueryBuilders.matchQuery("all","如家"));
  23. //发送请求
  24. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  25. AllMatch(response);
  26. }
  27. private void AllMatch(SearchResponse response) {
  28. //解析响应的json
  29. SearchHits hits = response.getHits();
  30. //拉取总条数
  31. long value = hits.getTotalHits().value;
  32. //来取文档数组
  33. SearchHit[] hits1 = hits.getHits();
  34. //遍历数组进行反序列化
  35. for (SearchHit documentFields : hits1) {
  36. //读取文档score
  37. String json = documentFields.getSourceAsString();
  38. HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
  39. }
  40. System.out.println(response);
  41. }
  42. @Test
  43. private void testBool() throws IOException {
  44. //准备REQUEST
  45. SearchRequest request = new SearchRequest("hotel");
  46. //准备DSL
  47. //BooleanQuery
  48. BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  49. //添加term
  50. boolQueryBuilder.must(QueryBuilders.termQuery("city","杭州"));
  51. //添加range
  52. boolQueryBuilder.must(QueryBuilders.rangeQuery("parice").lt("杭州"));
  53. //发送请求
  54. SearchResponse response = client.search(request, RequestOptions.DEFAULT);
  55. AllMatch(response);
  56. }
  57. @BeforeEach
  58. void setUp() {
  59. client = new RestHighLevelClient(RestClient.builder(
  60. HttpHost.create("http://114.55.210.174:9200")
  61. ));
  62. }
  63. @AfterEach
  64. void tearDown() throws IOException {
  65. client.close();
  66. }
  67. }