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

es的优势

系列文章目录

提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
例如:第一章 Python 机器学习入门之pandas的使用


提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 系列文章目录
  • 前言
  • 一、es为什么比mysql快
  • 二、使用步骤
    • 1.引入库
    • 2. es查询语法
  • 三,api功能
  • 总结


前言

总结es优势


一、es为什么比mysql快

  1. es是一个基于Lucene引擎库,基于内存,查询速度比mysql,这个是在存储方式的比较
  2. 第二是数据存储方式,倒排索引,存储方式,可以快速找到数据的大概位置,文档列表,利用二叉查询方法进行寻找方式
  3. es支持复杂的语法格式,寻找附近酒店,进行分页
  4. 缺点
  5. 过于占内存

二、使用步骤

1.引入库

代码如下(示例):

package com.cn;import com.alibaba.fastjson.JSON;
import com.cn.mapper.ESMapper;
import com.cn.pojo.Hotel;
import com.cn.pojo.TbHotel;
import com.cn.pojo.vo.TbHotelVo;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest
public class EsTest {@Autowiredprivate RestHighLevelClient client;@Autowiredprivate ESMapper esMapper;@BeforeEachvoid setUp() {this.client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.36.128:9200")));}@AfterEachvoid tearDown() throws IOException {this.client.close();}/*** 判断索引是否存在* @throws IOException*/@Testpublic void  getIndexRequest() throws IOException {GetIndexRequest request = new GetIndexRequest("tiantian");boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);System.out.println(exists?"不能再":"我问");}/*** 批量导入文档* @throws IOException*/@Testpublic void c() throws IOException {List<Hotel> hotels = new ArrayList<>();for (int i = 0; i < 50; i++) {Hotel hotel = new Hotel();hotel.setId(Long.valueOf(i));hotel.setAge(i);hotel.setAddress("我的地址方式"+i);hotel.setTime(new Date());hotel.setName("将来"+i);hotel.setLatLon("23.5","3"+i);hotel.setLocation("23.5","3"+i);hotels.add(hotel);}//批量导入BulkRequest bulkRequest = new BulkRequest();//转化文档for (Hotel hotel : hotels) {bulkRequest.add(new IndexRequest("tiantian").id(hotel.getId().toString()).source(JSON.toJSONString(hotel), XContentType.JSON));}//发送请求BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);System.out.println(bulk);}/*** 导入数据信息* @throws IOException*/@Testpublic void bulkRequest() throws IOException {BulkRequest bulkRequest = new BulkRequest();List<TbHotel> tbHotels = esMapper.selectList(null);for (TbHotel tbHotel : tbHotels) {TbHotelVo tbHotelVo = new TbHotelVo(tbHotel);bulkRequest.add(new IndexRequest("hotel").id(tbHotelVo.getId().toString()).source(JSON.toJSONString(tbHotelVo),XContentType.JSON));}client.bulk(bulkRequest,RequestOptions.DEFAULT);}/*** 查询所有文档信息* @throws IOException*/@Testpublic void testMatchAll() throws IOException {SearchRequest request = new SearchRequest("hotel");request.source().query(QueryBuilders.matchAllQuery());SearchResponse response = client.search(request, RequestOptions.DEFAULT);for (SearchHit hit : response.getHits().getHits()) {String source = hit.getSourceAsString();System.out.println(source);}}/*** 准确查询* @throws IOException*/@Testpublic void matchQuery() throws IOException {SearchRequest request = new SearchRequest("hotel");request.source().query(QueryBuilders.termQuery("price","189"));SearchResponse response = client.search(request, RequestOptions.DEFAULT);for (SearchHit hit : response.getHits().getHits()) {String sourceAsString = hit.getSourceAsString();System.out.println(sourceAsString);}}/*** 布尔查询方式* 查询名字叫做如家* 价格200* 地址在上海*/@Testpublic void boolQuery() throws IOException {SearchRequest request = new SearchRequest("hotel");BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();boolQuery.mustNot(QueryBuilders.rangeQuery("price").gte("400"));boolQuery.must(QueryBuilders.matchQuery("city","上海"));boolQuery.must(QueryBuilders.matchQuery("name","如家"));request.source().query(boolQuery);for (SearchHit hit : client.search(request, RequestOptions.DEFAULT).getHits().getHits()) {String sourceAsString = hit.getSourceAsString();System.out.println(sourceAsString);}}/*** bool查询方式* @throws IOException*/@Testpublic void testBoole() throws IOException {SearchRequest request = new SearchRequest("hotel");BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();boolQuery.must(QueryBuilders.matchQuery("name","如家"));request.source().query(boolQuery);for (SearchHit hit : client.search(request, RequestOptions.DEFAULT).getHits()) {System.out.println(hit.getSourceAsString());}}/*** 根据经纬度查询方式* @throws IOException*/@Testpublic void geoPoint() throws IOException {SearchRequest request = new SearchRequest("hotel");request.source().sort(SortBuilders.geoDistanceSort("lonAndLat",new GeoPoint("31.2,121.5")).order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));SearchResponse response = client.search(request, RequestOptions.DEFAULT);for (SearchHit hit : response.getHits().getHits()) {TbHotel tbHotel = JSON.parseObject(hit.getSourceAsString(), TbHotel.class);System.out.println(tbHotel.getLonAndLat());}}@Testpublic void testMat() throws IOException {SearchRequest request = new SearchRequest("hotel");request.source().query(QueryBuilders.matchQuery("name","如家"));SearchResponse response = client.search(request, RequestOptions.DEFAULT);for (SearchHit hit : response.getHits().getHits()) {System.out.println(hit.getSourceAsString());}}
}

2. es查询语法

代码如下(示例):


//添加索引
PUT /tiantian
{"mappings": {"properties": {"name":{"type": "text", "analyzer": "ik_smart"},"age":{"type": "integer", "index": false}}}
}//查询索引
GET /tiantian//查询文档信息
GET /tiantian/_doc/1//添加字段信息
PUT /tiantian/_mapping
{"properties":{"address":{"type":"text","index":false}}
}//添加数据文档数据信息
POST /tiantian/_doc/1
{"address":"巴黎","name":"太牛龙","age":123
}//查询经纬度
GET /hotel/_search
{"query": {"match_all": {}},"sort": [{"price": {"order": "desc"}},{"_geo_distance": {"lonAndLat": {"lat": 31.2,"lon": 121.5},"order": "asc"}}]
}POST /hotel/_update/1902197537
{"doc": {"isAD": true}
}
POST /hotel/_update/2056126831
{"doc": {"isAD": true}
}
POST /hotel/_update/1989806195
{"doc": {"isAD": true}
}
POST /hotel/_update/2056105938
{"doc": {"isAD": true}
}GET /hotel/_search
{"query": {"function_score": {"query": {"match": {"name": "外滩"}},"functions": [{"filter": { "term": {"id": "1"}},"weight": 10}],"boost_mode": "multiply"}},"from": 1,"size": 10
}GET /hotel/_search
{"query": {"function_score": {"query": {"match": {"name": "如家"}},"functions": [{"filter": {"term": {"name": "339952837"}}, "weight": 10}],"boost_mode": "sum"}}
}GET /hotel/_search
{"query": {"match_all": {}}
}GET /hotelGET /hotel/_search
{"size": 0, "aggs": {"brandAgg": {"terms": {"field": "brand.keyword"}}}}GET /hotel/_search
{"query": {"match": {"name": "东方明珠"}}
}

三,api功能

@Overridepublic PageResult search(RequestParams params) throws IOException {//1.准备发送SearchRequest request = new SearchRequest("hotel");//2.准备布尔条件BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();//3.判断是否存在String key = params.getKey();if (key==null || "".equals(key)){boolQuery.must(QueryBuilders.matchAllQuery());}else {boolQuery.must(QueryBuilders.matchQuery("name",key));}Integer size = params.getSize();Integer page = params.getPage();request.source().from((page - 1) * size).size(size);request.source().query(boolQuery);String location = params.getLocation();//得出具体路径if (location!=null && !location.equals("")){request.source().sort(SortBuilders.geoDistanceSort("lonAndLat",new GeoPoint(location)).order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));}//相关性算法FunctionScoreQueryBuilder scoreQuery = QueryBuilders.functionScoreQuery(boolQuery,new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD", true),ScoreFunctionBuilders.weightFactorFunction(10))});request.source().query(scoreQuery);SearchResponse response = client.search(request, RequestOptions.DEFAULT);return  handleResponse(response);}

根据经纬度查询方式
在这里插入图片描述

//得出具体路径if (location!=null && !location.equals("")){request.source().sort(SortBuilders.geoDistanceSort("lonAndLat",new GeoPoint(location)).order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));}

相关性算法

请添加图片描述

       //相关性算法FunctionScoreQueryBuilder scoreQuery = QueryBuilders.functionScoreQuery(boolQuery,new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery("isAD", true),ScoreFunctionBuilders.weightFactorFunction(10))});

总结

  1. es高效,速度快,基于lu的内存数据库,采用倒序索引的方式,倒叙索引好处,我们之前数据库根据id找到值,倒排索引的方式,es默认创建索引,根据值找到,对应的文档列表,文档列表根据二分查找方式,找到对应的值
  2. es强大的api功能普通基于内存的数据库的方式,比如redis功能,适合做缓存,没有强大的api,不能做复杂的功能,es有强大api,分页,查询,联合查询,经纬度查询,相关性质查询方式

相关文章:

  • Lec14 File systems 笔记
  • 前端新手Vue3+Vite+Ts+Pinia+Sass项目指北系列文章 —— 第一章 技术栈简介
  • 奇瑞金融——汽车金融行业架构设计
  • 无线WiFi安全渗透与攻防(六)之WEP破解-Gerix-wifi-cracker自动化破解WEP加密
  • 让文字在盒子中水平居中与垂直居中
  • 6.9平衡二叉树(LC110-E)
  • RT-Thread STM32F407 BMI088--SPI
  • iptables详解:链、表、表链关系、规则的基本使用
  • 本地jar导入maven
  • 【2023春李宏毅机器学习】生成式学习的两种策略
  • 计算机毕业设计选题推荐-高校后勤报修微信小程序/安卓APP-项目实战
  • 小美的排列构造
  • Java Web 实战 19 - What‘s HTTP ?
  • 75基于matlab的模拟退火算法优化TSP(SA-TSP),最优路径动态寻优,输出最优路径值、路径曲线、迭代曲线。
  • 重磅 | 进一步夯实生态建设,朗思科技与阿里龙蜥完成兼容性认证
  • [分享]iOS开发-关于在xcode中引用文件夹右边出现问号的解决办法
  • [译]CSS 居中(Center)方法大合集
  • 《剑指offer》分解让复杂问题更简单
  • CODING 缺陷管理功能正式开始公测
  • Cumulo 的 ClojureScript 模块已经成型
  • Docker 1.12实践:Docker Service、Stack与分布式应用捆绑包
  • ES6, React, Redux, Webpack写的一个爬 GitHub 的网页
  • Javascript Math对象和Date对象常用方法详解
  • JavaScript学习总结——原型
  • node-sass 安装卡在 node scripts/install.js 解决办法
  • Python 基础起步 (十) 什么叫函数?
  • Python学习笔记 字符串拼接
  • vue和cordova项目整合打包,并实现vue调用android的相机的demo
  • 思维导图—你不知道的JavaScript中卷
  • 微信开放平台全网发布【失败】的几点排查方法
  • 用 vue 组件自定义 v-model, 实现一个 Tab 组件。
  • 阿里云移动端播放器高级功能介绍
  • 策略 : 一文教你成为人工智能(AI)领域专家
  • ​html.parser --- 简单的 HTML 和 XHTML 解析器​
  • #QT(一种朴素的计算器实现方法)
  • #传输# #传输数据判断#
  • #图像处理
  • #我与Java虚拟机的故事#连载07:我放弃了对JVM的进一步学习
  • $.ajax,axios,fetch三种ajax请求的区别
  • (12)目标检测_SSD基于pytorch搭建代码
  • (ibm)Java 语言的 XPath API
  • (Spark3.2.0)Spark SQL 初探: 使用大数据分析2000万KF数据
  • (翻译)terry crowley: 写给程序员
  • (附源码)ssm航空客运订票系统 毕业设计 141612
  • (十八)用JAVA编写MP3解码器——迷你播放器
  • (转)利用ant在Mac 下自动化打包签名Android程序
  • (转)如何上传第三方jar包至Maven私服让maven项目可以使用第三方jar包
  • .net core webapi 部署iis_一键部署VS插件:让.NET开发者更幸福
  • .Net Winform开发笔记(一)
  • .NET版Word处理控件Aspose.words功能演示:在ASP.NET MVC中创建MS Word编辑器
  • .net开源工作流引擎ccflow表单数据返回值Pop分组模式和表格模式对比
  • .net生成的类,跨工程调用显示注释
  • .NET序列化 serializable,反序列化
  • 。Net下Windows服务程序开发疑惑
  • @RequestBody的使用