济南制作网站的公司,菏泽专业网站开发公司,深圳建设交易中心网站,wordpress获取指定图片文章目录 前提倒排索引MySQL、ES的区别和关联IK分词器索引库mapping属性索引库的crud 文档的crudRestClientDSL查询DSL 查询种类DSL query 基本语法 搜索结构处理排序分页高亮RestClient 前提
开源的搜索引擎#xff0c;从海量数据中快速找到需要的内容。#xff08;分词检索… 文章目录 前提倒排索引MySQL、ES的区别和关联IK分词器索引库mapping属性索引库的crud 文档的crudRestClientDSL查询DSL 查询种类DSL query 基本语法 搜索结构处理排序分页高亮RestClient 前提
开源的搜索引擎从海量数据中快速找到需要的内容。分词检索类似百度查询、博客文章关键词搜索 elasticsearch结合 Kibana、Logstas、Beats也就是 elastic stack简称ELK广泛应用于日志分析、实时监控。
JDK兼容性https://www.elastic.co/cn/support/matrix#matrix_jvm 操作系统兼容性https://www.elastic.co/cn/support/matrix 自身兼容性https://www.elastic.co/cn/support/matrix#matrix_compatibility 对于ES 8.1 及以上版本而言支持 JDK 17、JDK 18
docker安装步骤es、kibana、IK
倒排索引 MySQL、ES的区别和关联
mysql擅长事务操作ACID确保数据安全和一致性 ES擅长海量数据搜索、分析、计算
文档 elasticsearch是面向文档存储的JSON每一条数据就是一个文档
索引 es中的索引是指相同类型的文档集合即mysql中表的概念 映射索引中文档字段的约束比如名称、类型 IK分词器
作用
在创建倒排索引时对文档进行分词用户搜索时对内容进行分词
ik分词器的两种模式 POST /_analyze { “text”:“这是程序员的一次测试包含English”, “analyzer”:“ik_max_word” } ik_smart最小切分粗粒度分出来的词不会再细分程序员 ik_max_word最细切分细粒度分出来的词更多更细程序员、程序 拓展词条、停用词条
进入docker 创建的容器的插件目录找到Ik分词器下的 IKAnalyzer.cfg.xml 文件扩展词典在 中添加文件名称例如ext.dic停用词典在 中添加例如stopword.dic。当然之后需要你手段创建词典文件内容格式为一词一行。 索引库
mapping属性
mapping映射是对索引库中文档的约束。类似mysql对表单字段的约束
{id:[1, 2, 3, 4, 5],name:{firstname:明,lastname:李}
}type字段数据类型常见的类型有 字符串text可分词的文本、keyword不可分词的文本例如国家、品牌、IP地址布尔boolean日期date数值long、short、byte、integer、double、floatObject对象 es里面没有数组类型json格式key、value允许value有多个值。上图id字段 index是否创建索引默认为true。就是是否创建倒排索引不创建之后就不能通过它搜索。analyzer使用那种分词器properties该字段的子字段上面name
索引库的crud
# 建立索引库
PUT /linsy
{mappings: {properties: {info: {type: text,analyzer: ik_smart},email: {type: keyword,index: false},name: {type: object,properties: {firstname: {type: keyword},lastName: {type: keyword}}}}}
}
查询索引库 GET /索引库名 GET /linsy 删除索引库 DELETE /索引库名
ES 禁止修改索引库字段类型及属性会影响整个索引的结构但是允许在原有索引库中新增字段。 注意不能新增已有字段
PUT /索引库名/_mapping
{properties: {新字段名: {type: integer}}
}文档的crud
新增操作 POST /索引库名/_doc/文档id { “字段1”: 值1“, “字段2”: “值2”, “字段3”: “值3”, }
查询 GET /索引库名/_doc/文档id 删除 DELETE /索引库名/_doc/文档id
# 文档操作
# 插入
POST /linsy/_doc/1
{age: 11,email: linsylinsy.work,info: this is a first test 文档,name: {firstname: 明,lastName: 李}
}GET /linsy/_doc/1DELETE /linsy/_doc/1POST /linsy/_update/1
{doc:{age:1111}
}修改文档
全量修改删除旧文档添加新文档。就是将上面新增的 DSL 改为 PUT
PUT /索引库名/_doc/文档id
{字段1: 值1“,字段2: 值2,字段3: 值3,
}增量修改修改指定字段
POST /索引库名/_update/文档id
{doc:{字段名:新的值}
}RestClient
springboot 导入elasticsearch依赖需注意它默认使用的版本和springboot的版本一致你需要对应到安装在服务器上的版本。 dependencygroupIdorg.elasticsearch.client/groupIdartifactIdelasticsearch-rest-high-level-client/artifactId/dependencypropertiesjava.version8/java.versionelasticsearch.version7.17.11/elasticsearch.version/properties创建索引库的mapping映射
PUT /hotel
{mappings: {properties: {id:{type: keyword},name:{type: text,analyzer: ik_max_word,copy_to: all},address:{type: keyword,index: false},price:{type: integer},score:{type: integer},brand:{type: keyword,copy_to: all},city:{type: keyword},starName:{type: keyword},business:{type: keyword,copy_to: all},location:{type: geo_point},pic:{type: keyword,index: false},all:{type: text,analyzer: ik_max_word}}}
}RestHighLevelClient 的使用 RestHighLevelClient restHighLevelClient new RestHighLevelClient(RestClient.builder(HttpHost.create(http://http://192.168.52.150:9200)));// index的增删查CreateIndexRequest createIndexRequest new CreateIndexRequest(linsy);createIndexRequest.source(建立索引库语句put, XContentType.JSON);restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);restHighLevelClient.indices().delete(new DeleteIndexRequest(要删除的索引库名), RequestOptions.DEFAULT);// 判断是否存在boolean b restHighLevelClient.indices().exists(new GetIndexRequest(索引库名), RequestOptions.DEFAULT);es8.x已经弃用了RestHighLevelClient 官方创建RestClient文档
文档的crud 查询文档 Autowiredprivate IHotelService iHotelService;BeforeEachpublic void before() {restHighLevelClient new RestHighLevelClient(RestClient.builder(HttpHost.create(http://192.168.52.150:9200)));}AfterEachpublic void after() throws IOException {restHighLevelClient.close();}Testpublic void addDocumentTest() throws IOException {Hotel hotel iHotelService.getById(61075);HotelDoc hotelDoc new HotelDoc(hotel);IndexRequest indexRequest new IndexRequest(hotel).id(hotel.getId().toString());indexRequest.source(JSON.toJSONString(hotelDoc), XContentType.JSON);restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);}Testpublic void queryDocumentTest() throws IOException {GetResponse getResponse restHighLevelClient.get(new GetRequest(hotel, 61075), RequestOptions.DEFAULT);String json getResponse.getSourceAsString();System.out.println(json);}Testpublic void updateDocumentTest() throws IOException {UpdateRequest updateRequest new UpdateRequest(hotel, 61075);updateRequest.doc(city, 北京,score, 90);restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);}Testpublic void deleteDocumentTest() throws IOException {restHighLevelClient.delete(new DeleteRequest(hotel, 61075), RequestOptions.DEFAULT);}Testpublic void batchAdd() throws IOException {BulkRequest bulkRequest new BulkRequest();ListHotel list iHotelService.list();for (Hotel hotel : list) {HotelDoc hotelDoc new HotelDoc(hotel);bulkRequest.add(new IndexRequest(hotel).id(hotel.getId().toString()).source(JSON.toJSONString(hotelDoc), XContentType.JSON));}restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);}
DSL
查询
DSL 查询种类
查询所有查询所有数据一般在测试时使用。march_all但是一般显示全部有一个分页的功能全文检索full text查询利用分词器对用户的输入内容进行分词然后去倒排索引库匹配。例如 match_querymutil_match_query 精确查询根据精确词条值查询数据一般查找的时keyword、数值、日期、boolean等字段。例如 idstermrange 地理查询geo根据经纬度查询例如 geo_distancegeo_bounding_box 复合compound查询复合查询时将上面各种查询条件组合在一起合并查询条件。例如 boolfuncation_score
DSL query 基本语法
# DSL查询
GET /indexName/_search
{query:{查询类型:{查询条件:条件值}}
}match 与 multi_match 的与别是前者根据单字段查后者根据多字段查。 参与搜索的字段越多查询效率越低建议利用copy_to将多个检索字段放在一起然后使用match—all字段查。
GET /hotel/_search
{query: {match: {city: 上海}}
}GET /hotel/_search
{query: {match: {all: 如家}}
}GET /hotel/_search{query: {multi_match: {query: 如家,fields: [name,brand,business]}}}精确查询 term字段全值匹配range字段范围匹配。 精确查询一般查找keyword、数值、boolean等不可分词的字段
# term
GET /hotel/_search
{query: {term: {city: {value: 北京}}}
}
# range
GET /hotel/_search
{query: {range: {price: {gt: 1000,lt: 2000}}}
}地理查询
GET /hotel/_search
{query: {geo_bounding_box: {location: {top_left: {lat: 31.1,lon: 121.5},bottom_right: {lat: 30.9,lon: 121.7}}}}
}GET /hotel/_search
{query: {geo_distance: {distance: 20km,location: {lat: 31.13,lon: 121.8}}}
}复合查询compound 将简单查询条件组合在一起实现复杂搜索逻辑。
function score算分函数查询可以控制文档的相关性算分控制排名。例如百度竞价
es在5.1及之后就弃用了 TF-IDF 算法开始采用 BM25算法。BM25算法不会因为词的出现频率变大而导致算分无限增大会逐渐趋近一个值
function score query 可以修改文档相关性算分得到新的算分。 三要素
过滤条件决定哪些条件要加分算分函数如何计算function score加权方式function score 与 query score如何运算
GET /hotel/_search
{query: {function_score: {query: {match: {all: 如家酒店}},functions: [{filter: {term: {city: 上海}},weight: 10}],boost_mode: sum}}
}boolean query布尔查询是一个或多个子查询的组合。
must必须匹配每个子查询类似”and“should选择性匹配子查询类似”or“must_not必须不匹配不参与算分类似”非“filter必须匹配不参与算分
GET /hotel/_search
{query: {bool: {must: [{match: {all: 上海}}],must_not: [{range: {price: {gt: 500}}}],filter: [{geo_distance: {distance: 10km,location: {lat: 31.21,lon: 121.5}}}]}}
}搜索结构处理
排序
es支持对搜索结构进行排序默认是根据相关度算分_score进行排序。可以排序的字段有keyword数值、地理坐标、日期类型等。
GET /hotel/_search
{query: {match_all: {}},sort: [{id: {order: desc}}]
}
GET /hotel/_search
{query: {match_all: {}},sort: [{_geo_distance: {location: {lat: 31.2,lon: 121.5},order: asc,unit: km}}]
}这个排序的结果就是相聚的公里数。
分页 针对深度分页ES给出了两种方案
search after分页时需要排序原理是从上次的排序值开始末尾值查询下一页的数据。官方推荐使用不会太占内存。手机向下反动滚页。scroll原理是将排序数据形成快照保存在内存。不推荐
高亮 ES默认搜索字段和高亮字段必须一致否则不会高亮。或者使用 require_field_match: false 也能高亮。
最后将查询结果中 highlight 与 指定高亮的字段进行替换返回给前端就行。
RestClient 普通查询 Testpublic void testMatchAll() throws IOException {SearchRequest searchRequest new SearchRequest(hotel);searchRequest.source().query(QueryBuilders.matchAllQuery());SearchResponse searchResponse restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);SearchHits searchHits searchResponse.getHits();long value searchHits.getTotalHits().value;System.out.println(value);SearchHit[] hits searchHits.getHits();System.out.println(hits[0]);HotelDoc hotelDoc JSON.parseObject(hits[0].getSourceAsString(), HotelDoc.class);System.out.println(hotelDoc);}QueryBuilders.matchAllQuery()QueryBuilders.matchQuery(all,如家)QueryBuilders.multiMatchQuery(如家,name,brand,business)QueryBuilders.termQuery(city,上海)QueryBuilders.rangeQuery(price).gt(100).lt(400)BoolQueryBuilder boolQueryBuilder QueryBuilders.boolQuery();boolQueryBuilder.must(QueryBuilders.termQuery(city,北京));boolQueryBuilder.filter(QueryBuilders.rangeQuery(price).gt(100).lt(400));
分页和排序 public void testPageAndSort() throws IOException {int pageNum 2, pageSize 10;SearchRequest searchRequest new SearchRequest(hotel);BoolQueryBuilder boolQueryBuilder QueryBuilders.boolQuery();TermQueryBuilder termQueryBuilder QueryBuilders.termQuery(brand, 如家);MatchQueryBuilder matchQueryBuilder QueryBuilders.matchQuery(all, 北京);boolQueryBuilder.must(termQueryBuilder);boolQueryBuilder.must(matchQueryBuilder);searchRequest.source().query(boolQueryBuilder);searchRequest.source().from((pageNum - 1) * pageSize).size(pageSize);searchRequest.source().sort(price, SortOrder.ASC);SearchResponse searchResponse restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);SearchHit[] hits searchResponse.getHits().getHits();for (SearchHit hit : hits) {String source hit.getSourceAsString();HotelDoc hotelDoc JSON.parseObject(source, HotelDoc.class);System.out.println(hotelDoc);}}高亮 public void testHighLight() throws IOException {SearchRequest searchRequest new SearchRequest(hotel);searchRequest.source().query(QueryBuilders.matchQuery(all,如家));searchRequest.source().highlighter(new HighlightBuilder().field(name).requireFieldMatch(false));SearchResponse searchResponse restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);SearchHit[] hits searchResponse.getHits().getHits();for (SearchHit hit : hits) {String source hit.getSourceAsString();HotelDoc hotelDoc JSON.parseObject(source, HotelDoc.class);MapString, HighlightField highlightFields hit.getHighlightFields();if(!highlightFields.isEmpty()){HighlightField highlightField highlightFields.get(name);//一般value只有一个元素取数组第一个String name highlightField.getFragments()[0].string();hotelDoc.setName(name);}System.out.println(hotelDoc);}}让指定酒店置顶 function_score 广告业务 // 算分控制FunctionScoreQueryBuilder functionScoreQueryBuilder QueryBuilders.functionScoreQuery(// 原始查询boolQueryBuilder,// FunctionScore 数组new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.termQuery(isAD, true),ScoreFunctionBuilders.weightFactorFunction(10))});
文章转载自: http://www.morning.lpsjs.com.gov.cn.lpsjs.com http://www.morning.lzwfg.cn.gov.cn.lzwfg.cn http://www.morning.mlnby.cn.gov.cn.mlnby.cn http://www.morning.ypbp.cn.gov.cn.ypbp.cn http://www.morning.shsh1688.com.gov.cn.shsh1688.com http://www.morning.zrpbf.cn.gov.cn.zrpbf.cn http://www.morning.brbnc.cn.gov.cn.brbnc.cn http://www.morning.qnrpj.cn.gov.cn.qnrpj.cn http://www.morning.lhyhx.cn.gov.cn.lhyhx.cn http://www.morning.pxbky.cn.gov.cn.pxbky.cn http://www.morning.lwrks.cn.gov.cn.lwrks.cn http://www.morning.ptzbg.cn.gov.cn.ptzbg.cn http://www.morning.stfdh.cn.gov.cn.stfdh.cn http://www.morning.krjyq.cn.gov.cn.krjyq.cn http://www.morning.tftw.cn.gov.cn.tftw.cn http://www.morning.lrdzb.cn.gov.cn.lrdzb.cn http://www.morning.knryp.cn.gov.cn.knryp.cn http://www.morning.fssmx.com.gov.cn.fssmx.com http://www.morning.nysjb.cn.gov.cn.nysjb.cn http://www.morning.cpmwg.cn.gov.cn.cpmwg.cn http://www.morning.elsemon.com.gov.cn.elsemon.com http://www.morning.fnpyk.cn.gov.cn.fnpyk.cn http://www.morning.mmosan.com.gov.cn.mmosan.com http://www.morning.mxdiy.com.gov.cn.mxdiy.com http://www.morning.jzxqj.cn.gov.cn.jzxqj.cn http://www.morning.fpxyy.cn.gov.cn.fpxyy.cn http://www.morning.cpnsh.cn.gov.cn.cpnsh.cn http://www.morning.kkrnm.cn.gov.cn.kkrnm.cn http://www.morning.pghfy.cn.gov.cn.pghfy.cn http://www.morning.china-cj.com.gov.cn.china-cj.com http://www.morning.ttshf.cn.gov.cn.ttshf.cn http://www.morning.bnqcm.cn.gov.cn.bnqcm.cn http://www.morning.tqjks.cn.gov.cn.tqjks.cn http://www.morning.pkggl.cn.gov.cn.pkggl.cn http://www.morning.zhmgcreativeeducation.cn.gov.cn.zhmgcreativeeducation.cn http://www.morning.nzdks.cn.gov.cn.nzdks.cn http://www.morning.tbhlc.cn.gov.cn.tbhlc.cn http://www.morning.nfnxp.cn.gov.cn.nfnxp.cn http://www.morning.tdcql.cn.gov.cn.tdcql.cn http://www.morning.mhpkz.cn.gov.cn.mhpkz.cn http://www.morning.ylyzk.cn.gov.cn.ylyzk.cn http://www.morning.wqhlj.cn.gov.cn.wqhlj.cn http://www.morning.xyyplp.cn.gov.cn.xyyplp.cn http://www.morning.yrdn.cn.gov.cn.yrdn.cn http://www.morning.ffksr.cn.gov.cn.ffksr.cn http://www.morning.trpq.cn.gov.cn.trpq.cn http://www.morning.xrpwk.cn.gov.cn.xrpwk.cn http://www.morning.mqwnp.cn.gov.cn.mqwnp.cn http://www.morning.rgwrl.cn.gov.cn.rgwrl.cn http://www.morning.rjfr.cn.gov.cn.rjfr.cn http://www.morning.wmhlz.cn.gov.cn.wmhlz.cn http://www.morning.wmdqc.com.gov.cn.wmdqc.com http://www.morning.dhwyl.cn.gov.cn.dhwyl.cn http://www.morning.wdpt.cn.gov.cn.wdpt.cn http://www.morning.nwqyq.cn.gov.cn.nwqyq.cn http://www.morning.lnnc.cn.gov.cn.lnnc.cn http://www.morning.rqqn.cn.gov.cn.rqqn.cn http://www.morning.cfmrb.cn.gov.cn.cfmrb.cn http://www.morning.yptwn.cn.gov.cn.yptwn.cn http://www.morning.smnxr.cn.gov.cn.smnxr.cn http://www.morning.hbjqn.cn.gov.cn.hbjqn.cn http://www.morning.tlyms.cn.gov.cn.tlyms.cn http://www.morning.dgxrz.cn.gov.cn.dgxrz.cn http://www.morning.nqlnd.cn.gov.cn.nqlnd.cn http://www.morning.pkdng.cn.gov.cn.pkdng.cn http://www.morning.rlhh.cn.gov.cn.rlhh.cn http://www.morning.nsncq.cn.gov.cn.nsncq.cn http://www.morning.ydyjf.cn.gov.cn.ydyjf.cn http://www.morning.kpnpd.cn.gov.cn.kpnpd.cn http://www.morning.tzmjc.cn.gov.cn.tzmjc.cn http://www.morning.wzjhl.cn.gov.cn.wzjhl.cn http://www.morning.wxrbl.cn.gov.cn.wxrbl.cn http://www.morning.fbmrz.cn.gov.cn.fbmrz.cn http://www.morning.yhljc.cn.gov.cn.yhljc.cn http://www.morning.zsthg.cn.gov.cn.zsthg.cn http://www.morning.rzbcz.cn.gov.cn.rzbcz.cn http://www.morning.dbtdy.cn.gov.cn.dbtdy.cn http://www.morning.rmfwh.cn.gov.cn.rmfwh.cn http://www.morning.pkggl.cn.gov.cn.pkggl.cn http://www.morning.webife.com.gov.cn.webife.com