Skip to content
章节导航

SpringBoot 3.x 操作 ES 8.x 原始 StringQuery 搜索

什么是StringQuery

  • 将 Elasticsearch 查询作为 JSON 字符串,更适合对 Elasticsearch 查询的语法比较了解的人
  • 也更方便使用 kibana 或 postman 等客户端工具行进调试

案例一

布尔 must 查询,搜索标题有 架构 关键词,描述有 spring 关键字,时长范围是 10~6000 之间的

原始 DSL 查询

shell
GET /video/_search
{
  "query": {
    "bool": {
      "must": [{
        "match": {
          "title": "架构"
        }
      }, {
        "match": {
          "description": "spring"
        }          
      }, {
        "range": {
          "duration": {
            "gte": 10,
            "lte": 6000
          }
        }
      }]
    }
  }
}

SpringBoot + SpringData 查询

java
@Test
    void stringQuery() {

        //搜索标题有 架构 关键词,描述有 spring关键字,时长范围是 10~6000之间的
        String dsl = """
                   {"bool":{"must":[{"match":{"title":"架构"}},{"match":{"description":"spring"}},{"range":{"duration":{"gte":10,"lte":6000}}}]}}
                """;
        Query query = new StringQuery(dsl);

        List<SearchHit<VideoDTO>> searchHitList = restTemplate.search(query, VideoDTO.class).getSearchHits();

        // 获得searchHits,进行遍历得到content
        List<VideoDTO> videoDTOS = new ArrayList<>();
        searchHitList.forEach(hit -> {
            videoDTOS.add(hit.getContent());
        });
        System.out.println(videoDTOS);
    }