当前位置: 首页 > Linux

SpringBoot中ElasticSearch搜索引擎实践

时间:2023-04-06 06:50:08 Linux

实验环境ES版本:5.3.0springbt版本:1.5.9首先当然要安装elasticsearch环境,最好安装visual插件-在elasticsearch-head中方便我们直观的查看数据。Spring项目的创建没有什么特别需要说明的,但是有几点是必须要注意的。在创建新项目时,记得检查web和NoSQL中的Elasticsearch依赖项。我们用一张图来说明一下:工程自动生成后,pom.xml中会自动添加spring-boot-starter-data-elasticsearch的依赖:org.springframework.bootspring-boot-starter-data-elasticsearch1234本项目中,我们使用开源的基于restful的esjava客户端jest,所以我们还需要在pom.xml中添加jest依赖:io.searchboxjest1234另外必须添加jna依赖:net.java.dev.jnajna1234否则启动spring项目时,报错JNAnotfound。本机方法将被禁用。会报:项目配置文件application.yml需要配置es服务器地址为server:port:6325spring:elasticsearch:jest:uris:-http://113.209.119.170:9200#ES服务器地址!read-timeout:5000123456789代码组织我的项目代码组织如下:各部分代码详细解释如下,注释:Entity.javapackagecom.hansonwang99.springboot_es_demo.entity;importjava.io.Serializable;importorg.springframework.data.elasticsearch.annotations.Document;publicclassEntityimplementsSerializable{privatestaticfinallongserialVersionUID=-763638353551774166L;publicstaticfinalStringINDEX_NAME="index_entity";publicstaticfinalStringTYPE="tstype";private私有字符串id;(){极好的();}publicEntity(Longid,Stringname){this.id=id;this.name=名称;}publicLonggetId(){返回id;}publicvoidsetId(Longid){这个.id=id;}publicStringgetName(){返回名称;}publicvoidsetName(Stringname){this.name=name;包com.hansonwang99.springboot_es_demo.service;导入com.hansonwang99.springboot_es_demo.entity.Entity;导入java.util.List;公共接口TestService{voidsaveEntity(实体实体);voidsaveEntity(ListentityList);ListsearchEntity(StringsearchContent);}1234567891011121314TestServiceImpl.javapackagecom.hansonwang99.springboot_es_demo.service.impl;importjava.io.IOException;importjava.util.List;importcom.hansonwang99.springboot_es_demo.entity.Entity;导入com.hansonwang99.springboot_es_demo.service.TestService;导入org.elasticsearch.index.query.QueryBuilders;导入org.elasticsearch.search.builder.SearchSourceBuilder;导入org.slf4j.Logger;导入org.slf4j.LoggerFactory;导入org.springframework.beans.factory.annotation.Autowired;导入org.springframework.stereotype.Service;导入io.searchbox.client.JestClient;导入io.searchbox.client.JestResult;导入io.searchbox.core.Bulk;导入io.searchbox.core.Index;importio.searchbox.core.Search;@ServicepublicclassTestServiceImplimplementsTestService{privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(TestServiceImpl.class);@AutowiredprivateJestClientjestClient;@OverridepublicvoidsaveEntity(Entityentity){Indexindex=newIndex.Builder(entity).index(Entity.INDEX_NAME).type(Entity.TYPE).build();试试{jestClient.execute(index);LOGGER.info("ES插入完成");}catch(IOExceptione){e.printStackTrace();LOGGER.error(e.getMessage());}}/***批量保存内容到ES*/@OverridepublicvoidsaveEntity(ListentityList){Bulk.Builderbulk=newBulk.Builder();for(Entityentity:entityList){Indexindex=newIndex.Builder(entity).index(Entity.INDEX_NAME).type(Entity.TYPE).build();bulk.addAction(索引);}尝试{jestClient.execute(bulk.build());LOGGER.info("ES插入完成");}catch(IOExceptione){e.printStackTrace();LOGGER.error(e.getMessage());}}/***在ES中搜索内容*/@OverridepublicListsearchEntity(StringsearchContent){SearchSourceBuildersearchSourceBuilder=newSearchSourceBuilder();//searchSourceBuilder.query(QueryBuilders.queryStringQuery(searchContent));//searchSourceBuilder.field("名称");searchSourceBuilder.query(QueryBuilders.matchQuery("name",searchContent));搜索search=newSearch.Builder(searchSourceBuilder.toString()).addIndex(Entity.INDEX_NAME).addType(Entity.TYPE).build();尝试{JestResult结果=jestClient.execute(search);返回结果.getSourceAsObjectList(Entity.class);}catch(IOExceptione){LOGGER.error(e.getMessage());e.printStackTrace();}返回空值;}}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182EntityController.javapackagecom.hansonwang99.springboot_es_demo.controller;importjava.util.ArrayList;importjava.util.List;importcom.hansonwang99.springboot_es_demo.entity.Entity;importcom.hansonwang99.springboot_es_demo.service.TestService;importorg.apache.commons.lang.StringUtils;导入org.springframework.beans.factory.annotation.Autowired;导入org.springframework.web.bind.annotation.RequestMapping;导入org.springframework.web.bind.annotation.RequestMethod;导入org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/entityController")publicclassEntityController{@AutowiredTestServicecityESService;@RequestMapping(value="/save",method=RequestMethod.GET)publicStringsave(longid,Stringname){System.out.println("保存界面");if(id>0&&StringUtils.isNotEmpty(name)){EntitynewEntity=newEntity(id,name);ListaddList=newArrayList();addList.add(newEntity);cityESService.saveEntity(addList);返回“确定”;}else{返回“错误的输入值”;}}@RequestMapping(value="/search",method=RequestMethod.GET)publicListsave(Stringname){ListentityList=null;if(StringUtils.isNotEmpty(name)){entityList=cityESService.searchEntity(name);}返回实体列表;}}1234567891011121314151617181920212223242526272829303132333435363738394041424344实境实验添加几条数据,可以使用postman工具,也可以直接在浏览器中输入,比如添加如下的http/5slocalaveentity65条数据:?id=1&name=南京中山陵http://localhost:6325/entityController/save?id=2&name=中国南京分部范大学http://localhost:6325/entityController/save?id=3&name=南京夫子庙http://localhost:6325/entityController/save?id=4&name=杭州也很好http://localhost:6325/entityController/save?id=5&name=江南似乎没有京字城。12345数据插入效果如下(使用可视化插件elasticsearch-head查看):我们来做一个搜索测试:比如我要搜索关键词“南京”我们在浏览器中输入:http://localhost:6325/entityController/search?name=Nanjing1搜索结果如下:刚才插入的5条记录中,搜索出了4条包含关键字“Nanjing”的记录!当然,这里使用的是标准的分词方式,将每个中文单词视为一个term。搜索出所有包含关键字“南”和“京”的记录,但得分不同。当然,还有其他的分词方法,此时需要其他分词插件的支持,这里不再赘述,文章后面会继续探讨。如需更多资讯,请点击下图?(扫码加好友→备注66,不加备注拒绝添加)