当前位置: 首页 > news >正文

ES小总结

组合查询

FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(boolQuery,new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD",true),ScoreFunctionBuilders.weightFactorFunction(200))});

总代码:

public PageResult search(RequestParams params) {try {SearchRequest request = new SearchRequest("hotel");//准备DSLString key = params.getKey();//query//构建BooleanQueryBoolQueryBuilder boolQuery = QueryBuilders.boolQuery();//关键字搜索--> mustif (key == null || "".equals(key)) {boolQuery.must(QueryBuilders.matchAllQuery());} else {boolQuery.must(QueryBuilders.matchQuery("all", key));}//城市条件if (params.getCity() != null && !params.getCity().equals("")) {boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));}//品牌条件if (params.getBrand() != null && !params.getBrand().equals("")) {}//星级条件if (params.getStarName() != null && !params.getStarName().equals("")) {}//价格if (params.getMinPrice() != null && params.getMaxPrice() != null) {//range过滤boolQuery.filter(QueryBuilders.rangeQuery("price").lte(params.getMaxPrice()).gte(params.getMinPrice()));}//分页int page = params.getPage();int size = params.getSize();request.source().from((page - 1) * size).size(size);//排序String location = params.getLocation();if (location != null && !location.equals("")) {request.source().sort(SortBuilders.geoDistanceSort("location", new GeoPoint(location)).unit(DistanceUnit.KILOMETERS).order(SortOrder.ASC));}//算分控制FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(boolQuery,new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD",true),ScoreFunctionBuilders.weightFactorFunction(200))});request.source().query(functionScoreQuery);//发送请求SearchResponse response = client.search(request, RequestOptions.DEFAULT);return handleResponse(response);} catch (IOException e) {throw new RuntimeException(e);}}private PageResult handleResponse(SearchResponse response) {//解析响应SearchHits searchHits = response.getHits();//获取总条数Long total = searchHits.getTotalHits().value;//获取文档数组SearchHit[] hits = searchHits.getHits();//遍历数组,取出数据List<HotelDoc> hotels = new ArrayList<>();for (SearchHit hit : hits) {//获取文档的sourceString json = hit.getSourceAsString();//反序列化HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);//获取sort值Object[] sortValues = hit.getSortValues();if (sortValues.length > 0) {Object sortValue = sortValues[0];hotelDoc.setDistance(sortValue);}hotels.add(hotelDoc);}//构造返回对象PageResult result = new PageResult(hotels, total);return result;}

步骤总结:

  1. 准备request
  2. 准备DSL
  3. 利用client来发送请求
  4. 解析client的返回值

准备request

request分为创建、查询、删除、更新等操作。

Document文档的操作

创建

    void testAddDocument() throws IOException {Hotel hotel = hotelService.getById(61083L);HotelDoc hotelDoc=new HotelDoc(hotel);//创建request对象IndexRequest request=new IndexRequest("hotel").id(hotelDoc.getId().toString());//准备JSON文档request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);//发送请求client.index(request,RequestOptions.DEFAULT);}

查询

    void testGetDocumentById() throws IOException {GetRequest request=new GetRequest("hotel","61083");//获取响应GetResponse response=client.get(request,RequestOptions.DEFAULT);String json = response.getSourceAsString();HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);System.out.println(hotelDoc);}

删除

    void DeleteDocument() throws IOException {DeleteRequest request=new DeleteRequest("hotel","61083");client.delete(request,RequestOptions.DEFAULT);}

更新

    void testUpdateDocument() throws IOException {UpdateRequest request=new UpdateRequest("hotel","61083");//准备发送请求request.doc("price","123");client.update(request,RequestOptions.DEFAULT);}

Index索引的操作

创建

    void createHotelIndex() throws IOException {//创建Request对象CreateIndexRequest request = new CreateIndexRequest("hotel");//准备请求参数,DSL语句request.source(MAPPING_TEMPLATE, XContentType.JSON);//发送请求client.indices().create(request, RequestOptions.DEFAULT);}

删除

    void DeleteHotelIndex() throws IOException {//创建对象DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("hotel");//发送请求client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);}

Bool复合查询

BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();//创建boolQuery//根据must、should、filter等来填写查询条件boolQuery.must(QueryBuilders.matchQuery("all", key));boolQuery.filter(QueryBuilders.termQuboolQuery.filter(QueryBuilders.rangeQuery("price").lte(params.getMaxPrice()).gte(params.getMinPrice()));ery("city", params.getCity()));
http://www.lryc.cn/news/306751.html

相关文章:

  • vue2与vue3中父子组件传参的区别
  • 使用vuetify实现全局v-alert消息通知
  • CentOS 7.9上编译wireshark 3.6
  • 初学学习408之数据结构--数据结构基本概念
  • Java项目中必须使用本地缓存的几种情况
  • 【鸿蒙 HarmonyOS 4.0】TypeScript开发语言
  • Android java基础_异常
  • 高数考研 -- 公式总结(更新中)
  • 详解顺序结构滑动窗口处理算法
  • Java 8中使用Stream来操作集合
  • MATLAB环境下一种改进的瞬时频率(IF)估计方法
  • 解决:selenium web browser 的版本适配问题
  • pytest.param作为pytest.mark.parametrize的参数进行调用
  • 如何判断一个元素是否在可视区域中?
  • Go Run - Go 语言中的简洁指令
  • Spring全面精简总结
  • 低代码开发如何助力数字化企业管理系统平台构建
  • ElasticSearch之零碎知识点
  • 【春运抢票攻略浅析】
  • 【Java EE初阶二十五】简单的表白墙(一)
  • 人工智能的新浪潮:探索OpenAI的Sora视频模型及其对未来创作的影响
  • 【c语言】字符函数和字符串函数(上)
  • React18源码: schedule任务调度messageChannel
  • Jmeter 学习目录
  • 计算机网络 数据链路层课后题
  • 实现验证码功能
  • PyQt6的开发流程(密码生成小程序为例)
  • 思腾云计算中心 | 5千平米超大空间,基础设施完善,提供裸金属GPU算力租赁业务
  • 【Leetcode每日一题】二分查找 - 在排序数组中查找元素的第一个和最后一个位置(难度⭐⭐)(18)
  • 远程连接 vscode 出错 “远程主机可能不符合 glibc 和 libstdc++ VS Code 服务器的先决条件”