使用 Elasticsearch 优雅搭建自己的搜索系统
什么是elasticsearch
Elasticsearch 是一個(gè)開源的高度可擴(kuò)展的全文搜索和分析引擎,擁有查詢近實(shí)時(shí)的超強(qiáng)性能。
大名鼎鼎的Lucene 搜索引擎被廣泛用于搜索領(lǐng)域,但是操作復(fù)雜繁瑣,總是讓開發(fā)者敬而遠(yuǎn)之。而 Elasticsearch將 Lucene 作為其核心來(lái)實(shí)現(xiàn)所有索引和搜索的功能,通過(guò)簡(jiǎn)單的 RESTful 語(yǔ)法來(lái)隱藏掉 Lucene 的復(fù)雜性,從而讓全文搜索變得簡(jiǎn)單
ES在Lucene基礎(chǔ)上,提供了一些分布式的實(shí)現(xiàn):集群,分片,復(fù)制等。
搜索為什么不用MySQL而用es
我們本文案例是一個(gè)迷你商品搜索系統(tǒng),為什么不考慮使用MySQL來(lái)實(shí)現(xiàn)搜索功能呢?原因如下:
- MySQL默認(rèn)使用innodb引擎,底層采用b+樹的方式來(lái)實(shí)現(xiàn),而Es底層使用倒排索引的方式實(shí)現(xiàn),使用倒排索引支持各種維度的分詞,可以掌控不同粒度的搜索需求。(MYSQL8版本也支持了全文檢索,使用倒排索引實(shí)現(xiàn),有興趣可以去看看兩者的差別)
- 如果使用MySQL的%key%的模糊匹配來(lái)與es的搜索進(jìn)行比較,在8萬(wàn)數(shù)據(jù)量時(shí)他們的耗時(shí)已經(jīng)達(dá)到40:1左右,毫無(wú)疑問(wèn)在速度方面es完勝。
es在大廠中的應(yīng)用情況
- es運(yùn)用最廣泛的是elk組合來(lái)對(duì)日志進(jìn)行搜索分析
- 58安全部門、京東訂單中心幾乎全采用es來(lái)完成相關(guān)信息的存儲(chǔ)與檢索
- es在tob的項(xiàng)目中也用于各種檢索與分析
- 在c端產(chǎn)品中,企業(yè)通常自己基于Lucene封裝自己的搜索系統(tǒng),為了適配公司營(yíng)銷戰(zhàn)略、推薦系統(tǒng)等會(huì)有更多定制化的搜索需求
es客戶端選型
spring-boot-starter-data-elasticsearch
我相信你看到的網(wǎng)上各類公開課視頻或者小項(xiàng)目均推薦使用這款springboot整合過(guò)的es客戶端,但是我們要say no!
?
?
此圖是引入的最新版本的依賴,我們可以看到它所使用的es-high-client也為6.8.7,而es7.x版本都已經(jīng)更新很久了,這里許多新特性都無(wú)法使用,所以版本滯后是他最大的問(wèn)題。而且它的底層也是highclient,我們操作highclient可以更靈活。我呆過(guò)的兩個(gè)公司均未采用此客戶端。
elasticsearch-rest-high-level-client
這是官方推薦的客戶端,支持最新的es,其實(shí)使用起來(lái)也很便利,因?yàn)槭枪俜酵扑]所以在特性的操作上肯定優(yōu)于前者。而且該客戶端與TransportClient不同,不存在并發(fā)瓶頸的問(wèn)題,官方首推,必為精品!
搭建自己的迷你搜索系統(tǒng)
引入es相關(guān)依賴,除此之外需引入springboot-web依賴、jackson依賴以及l(fā)ombok依賴等。
<properties><es.version>7.3.2</es.version></properties><!-- high client--><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>${es.version}</version><exclusions><exclusion><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId></exclusion><exclusion><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>${es.version}</version></dependency><!--rest low client high client以來(lái)低版本client所以需要引入--><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-client</artifactId><version>${es.version}</version></dependency>es配置文件es-config.properties
es.host=localhost es.port=9200 es.token=es-token es.charset=UTF-8 es.scheme=httpes.client.connectTimeOut=5000 es.client.socketTimeout=15000封裝RestHighLevelClient
@Configuration @PropertySource("classpath:es-config.properties") public class RestHighLevelClientConfig {@Value("${es.host}")private String host;@Value("${es.port}")private int port;@Value("${es.scheme}")private String scheme;@Value("${es.token}")private String token;@Value("${es.charset}")private String charSet;@Value("${es.client.connectTimeOut}")private int connectTimeOut;@Value("${es.client.socketTimeout}")private int socketTimeout;@Beanpublic RestClientBuilder restClientBuilder() {RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(host, port, scheme));Header[] defaultHeaders = new Header[]{new BasicHeader("Accept", "*/*"),new BasicHeader("Charset", charSet),//設(shè)置token 是為了安全 網(wǎng)關(guān)可以驗(yàn)證token來(lái)決定是否發(fā)起請(qǐng)求 我們這里只做象征性配置new BasicHeader("E_TOKEN", token)};restClientBuilder.setDefaultHeaders(defaultHeaders);restClientBuilder.setFailureListener(new RestClient.FailureListener(){@Overridepublic void onFailure(Node node) {System.out.println("監(jiān)聽某個(gè)es節(jié)點(diǎn)失敗");}});restClientBuilder.setRequestConfigCallback(builder ->builder.setConnectTimeout(connectTimeOut).setSocketTimeout(socketTimeout));return restClientBuilder;}@Beanpublic RestHighLevelClient restHighLevelClient(RestClientBuilder restClientBuilder) {return new RestHighLevelClient(restClientBuilder);} }封裝es常用操作
@Service public class RestHighLevelClientService {@Autowiredprivate RestHighLevelClient client;@Autowiredprivate ObjectMapper mapper;/*** 創(chuàng)建索引* @param indexName* @param settings* @param mapping* @return* @throws IOException*/public CreateIndexResponse createIndex(String indexName, String settings, String mapping) throws IOException {CreateIndexRequest request = new CreateIndexRequest(indexName);if (null != settings && !"".equals(settings)) {request.settings(settings, XContentType.JSON);}if (null != mapping && !"".equals(mapping)) {request.mapping(mapping, XContentType.JSON);}return client.indices().create(request, RequestOptions.DEFAULT);}/*** 判斷 index 是否存在*/public boolean indexExists(String indexName) throws IOException {GetIndexRequest request = new GetIndexRequest(indexName);return client.indices().exists(request, RequestOptions.DEFAULT);}/*** 搜索*/public SearchResponse search(String field, String key, String rangeField, String from, String to,String termField, String termVal, String ... indexNames) throws IOException{SearchRequest request = new SearchRequest(indexNames);SearchSourceBuilder builder = new SearchSourceBuilder();BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();boolQueryBuilder.must(new MatchQueryBuilder(field, key)).must(new RangeQueryBuilder(rangeField).from(from).to(to)).must(new TermQueryBuilder(termField, termVal));builder.query(boolQueryBuilder);request.source(builder);log.info("[搜索語(yǔ)句為:{}]",request.source().toString());return client.search(request, RequestOptions.DEFAULT);}/*** 批量導(dǎo)入* @param indexName* @param isAutoId 使用自動(dòng)id 還是使用傳入對(duì)象的id* @param source* @return* @throws IOException*/public BulkResponse importAll(String indexName, boolean isAutoId, String source) throws IOException{if (0 == source.length()){//todo 拋出異常 導(dǎo)入數(shù)據(jù)為空}BulkRequest request = new BulkRequest();JsonNode jsonNode = mapper.readTree(source);if (jsonNode.isArray()) {for (JsonNode node : jsonNode) {if (isAutoId) {request.add(new IndexRequest(indexName).source(node.asText(), XContentType.JSON));} else {request.add(new IndexRequest(indexName).id(node.get("id").asText()).source(node.asText(), XContentType.JSON));}}}return client.bulk(request, RequestOptions.DEFAULT);}創(chuàng)建索引,這里的settings是設(shè)置索引是否設(shè)置復(fù)制節(jié)點(diǎn)、設(shè)置分片個(gè)數(shù),mappings就和數(shù)據(jù)庫(kù)中的表結(jié)構(gòu)一樣,用來(lái)指定各個(gè)字段的類型,同時(shí)也可以設(shè)置字段是否分詞(我們這里使用ik中文分詞器)、采用什么分詞方式。
@Testpublic void createIdx() throws IOException {String settings = "" +" {\n" +" \"number_of_shards\" : \"2\",\n" +" \"number_of_replicas\" : \"0\"\n" +" }";String mappings = "" +"{\n" +" \"properties\": {\n" +" \"itemId\" : {\n" +" \"type\": \"keyword\",\n" +" \"ignore_above\": 64\n" +" },\n" +" \"urlId\" : {\n" +" \"type\": \"keyword\",\n" +" \"ignore_above\": 64\n" +" },\n" +" \"sellAddress\" : {\n" +" \"type\": \"text\",\n" +" \"analyzer\": \"ik_max_word\", \n" +" \"search_analyzer\": \"ik_smart\",\n" +" \"fields\": {\n" +" \"keyword\" : {\"ignore_above\" : 256, \"type\" : \"keyword\"}\n" +" }\n" +" },\n" +" \"courierFee\" : {\n" +" \"type\": \"text\n" +" },\n" +" \"promotions\" : {\n" +" \"type\": \"text\",\n" +" \"analyzer\": \"ik_max_word\", \n" +" \"search_analyzer\": \"ik_smart\",\n" +" \"fields\": {\n" +" \"keyword\" : {\"ignore_above\" : 256, \"type\" : \"keyword\"}\n" +" }\n" +" },\n" +" \"originalPrice\" : {\n" +" \"type\": \"keyword\",\n" +" \"ignore_above\": 64\n" +" },\n" +" \"startTime\" : {\n" +" \"type\": \"date\",\n" +" \"format\": \"yyyy-MM-dd HH:mm:ss\"\n" +" },\n" +" \"endTime\" : {\n" +" \"type\": \"date\",\n" +" \"format\": \"yyyy-MM-dd HH:mm:ss\"\n" +" },\n" +" \"title\" : {\n" +" \"type\": \"text\",\n" +" \"analyzer\": \"ik_max_word\", \n" +" \"search_analyzer\": \"ik_smart\",\n" +" \"fields\": {\n" +" \"keyword\" : {\"ignore_above\" : 256, \"type\" : \"keyword\"}\n" +" }\n" +" },\n" +" \"serviceGuarantee\" : {\n" +" \"type\": \"text\",\n" +" \"analyzer\": \"ik_max_word\", \n" +" \"search_analyzer\": \"ik_smart\",\n" +" \"fields\": {\n" +" \"keyword\" : {\"ignore_above\" : 256, \"type\" : \"keyword\"}\n" +" }\n" +" },\n" +" \"venue\" : {\n" +" \"type\": \"text\",\n" +" \"analyzer\": \"ik_max_word\", \n" +" \"search_analyzer\": \"ik_smart\",\n" +" \"fields\": {\n" +" \"keyword\" : {\"ignore_above\" : 256, \"type\" : \"keyword\"}\n" +" }\n" +" },\n" +" \"currentPrice\" : {\n" +" \"type\": \"keyword\",\n" +" \"ignore_above\": 64\n" +" }\n" +" }\n" +"}";clientService.createIndex("idx_item", settings, mappings);}分詞技巧:
- 索引時(shí)最小分詞,搜索時(shí)最大分詞,例如"Java知音"索引時(shí)分詞包含Java、知音、音、知等,最小粒度分詞可以讓我們匹配更多的檢索需求,但是我們搜索時(shí)應(yīng)該設(shè)置最大分詞,用“Java”和“知音”去匹配索引庫(kù),得到的結(jié)果更貼近我們的目的,
- 對(duì)分詞字段同時(shí)也設(shè)置keyword,便于后續(xù)排查錯(cuò)誤時(shí)可以精確匹配搜索,快速定位。
我們向es導(dǎo)入十萬(wàn)條淘寶雙11活動(dòng)數(shù)據(jù)作為我們的樣本數(shù)據(jù),數(shù)據(jù)結(jié)構(gòu)如下所示
{"_id": "https://detail.tmall.com/item.htm?id=538528948719\u0026skuId=3216546934499","賣家地址": "上海","快遞費(fèi)": "運(yùn)費(fèi): 0.00元","優(yōu)惠活動(dòng)": "滿199減10,滿299減30,滿499減60,可跨店","商品ID": "538528948719","原價(jià)": "2290.00","活動(dòng)開始時(shí)間": "2016-11-11 00:00:00","活動(dòng)結(jié)束時(shí)間": "2016-11-11 23:59:59","標(biāo)題": "【天貓海外直營(yíng)】 ReFa CARAT RAY 黎琺 雙球滾輪波光美容儀","服務(wù)保障": "正品保證;贈(zèng)運(yùn)費(fèi)險(xiǎn);極速退款;七天退換","會(huì)場(chǎng)": "進(jìn)口尖貨","現(xiàn)價(jià)": "1950.00" }調(diào)用上面封裝的批量導(dǎo)入方法進(jìn)行導(dǎo)入
@Testpublic void importAll() throws IOException {clientService.importAll("idx_item", true, itemService.getItemsJson());}我們調(diào)用封裝的搜索方法進(jìn)行搜索,搜索產(chǎn)地為武漢、價(jià)格在11-149之間的相關(guān)酒產(chǎn)品,這與我們淘寶中設(shè)置篩選條件搜索商品操作一致。
@Testpublic void search() throws IOException {SearchResponse search = clientService.search("title", "酒", "currentPrice","11", "149", "sellAddress", "武漢");SearchHits hits = search.getHits();SearchHit[] hits1 = hits.getHits();for (SearchHit documentFields : hits1) {System.out.println( documentFields.getSourceAsString());}}我們得到以下搜索結(jié)果,其中_score為某一項(xiàng)的得分,商品就是按照它來(lái)排序。
{"_index": "idx_item","_type": "_doc","_id": "Rw3G7HEBDGgXwwHKFPCb","_score": 10.995819,"_source": {"itemId": "525033055044","urlId": "https://detail.tmall.com/item.htm?id=525033055044&skuId=def","sellAddress": "湖北武漢","courierFee": "快遞: 0.00","promotions": "滿199減10,滿299減30,滿499減60,可跨店","originalPrice": "3768.00","startTime": "2016-11-01 00:00:00","endTime": "2016-11-11 23:59:59","title": "酒嗨酒 西班牙原瓶原裝進(jìn)口紅酒蒙德干紅葡萄酒6只裝整箱送酒具","serviceGuarantee": "破損包退;正品保證;公益寶貝;不支持7天退換;極速退款","venue": "食品主會(huì)場(chǎng)","currentPrice": "151.00"}}擴(kuò)展性思考
- 商品搜索權(quán)重?cái)U(kuò)展,我們可以利用多種收費(fèi)方式智能為不同店家提供增加權(quán)重,增加曝光度適應(yīng)自身的營(yíng)銷策略。同時(shí)我們經(jīng)常發(fā)現(xiàn)淘寶搜索前列的商品許多為我們之前查看過(guò)的商品,這是通過(guò)記錄用戶行為,跑模型等方式智能為這些商品增加權(quán)重。
- 分詞擴(kuò)展,也許因?yàn)槟承┥唐返奶厥庑?#xff0c;我們可以自定義擴(kuò)展分詞字典,更精準(zhǔn)、人性化的搜索。
- 高亮功能,es提供highlight高亮功能,我們?cè)谔詫毶峡吹降纳唐氛故局袑?duì)搜索關(guān)鍵字高亮,就是通過(guò)這種方式來(lái)實(shí)現(xiàn)。
項(xiàng)目地址
https://github.com/Motianshi/alldemo/tree/master/demo-search?
總結(jié)
以上是生活随笔為你收集整理的使用 Elasticsearch 优雅搭建自己的搜索系统的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Flutter 核心原理与混合开发模式
- 下一篇: 复方菝葜颗粒_功效作用注意事项用药禁忌用