前言
本文介绍了如何整合搜索引擎elasticsearch与springboot,对外提供数据查询接口。
开发环境
组件介绍:
- elasticsearch:搜索引擎,用于存储待搜索数据
- logstash:用于将mysql中的商品数据同步到搜索引擎中
- elasticsearch-head(可选):elasticsearch可视化工具
- kibana(可选):elasticsearch可视化工具
本文测试环境:
- springboot:1.5.16
- elasticsearch:2.3.5(springboot1.5仅支持2.x的es)
- logstash:6.5.4
开发步骤
使用Docker部署elasticsearch
- docker下一键启动es,可根据需要的版本号对语句做修改
sudo docker run -it --rm --name elasticsearch -d -p 9200:9200 -p 9300:9300 elasticsearch:2.3.5 复制代码
注意到该命令:
- --rm参数:容器终止后销毁
- -d:后台进程
- -p 9200:9200 -p 9300:9300:开放了9200端口和9300端口
得到如图:
此时打开网页localhost:9200即可查看状态,显示类似为:
{ "name" : "Ant-Man", "cluster_name" : "elasticsearch", "version" : { "number" : "2.3.5", "build_hash" : "90f439ff60a3c0f497f91663701e64ccd01edbb4", "build_timestamp" : "2016-07-27T10:36:52Z", "build_snapshot" : false, "lucene_version" : "5.5.0" }, "tagline" : "You Know, for Search" } 复制代码
注意:docker的es默认对0.0.0.0公网开放
下载并使用logstash并导入数据
schedule => "* * * * *"
默认为每分钟同步一次
input { jdbc { jdbc_connection_string => "jdbc:mysql://localhost:3306/pm_backend" jdbc_user => "root" jdbc_password => "xxxxxxxxxx" jdbc_driver_library => "xxxxxxxx/mysql-connector-java-5.1.6.jar" jdbc_driver_class => "com.mysql.jdbc.Driver" jdbc_paging_enabled => "true" jdbc_page_size => "5000" statement=> "select * from pm_jd_item" schedule => "* * * * *" type => "pm_jd_item" } } output { elasticsearch { hosts => "localhost:9200" index => "pm_backend" document_type => "%{type}" document_id => "%{id}" } stdout { codec => json_lines } } 复制代码
在logstash目录下执行命令,完成数据的导入:
bin/logstash -f jdbc.conf 复制代码
得到如图:
同步完成后,使用elasticsearch-head查看(或者用kibana,请随意):
整合进springboot
- 添加pom.xml
<!-- 搜索引擎:elastic-search--> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>2.4.6</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-elasticsearch</artifactId> </dependency> 复制代码
- 修改application.properties
# elasticsearch spring.data.elasticsearch.cluster-name=elasticsearch #节点地址,多个节点用逗号隔开 spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300 #spring.data.elasticsearch.local=false spring.data.elasticsearch.repositories.enable=true 复制代码
- 在需要进行搜索的实体类上添加@Document、@Id、@Field等标注,本例为JdItem.java
@Document(indexName = "pm_backend", type = "pm_jd_item") public class JdItem implements Serializable { @Id private Integer id; @Field(type = FieldType.Long) private Long itemId; @Field(type = FieldType.Long) private Long categoryId; @Field(type = FieldType.String) private String name; 复制代码
- 添加JdItemRepository继承ElasticsearchRepository
public interface JdItemRepository extends ElasticsearchRepository<JdItem, Integer>{ } 复制代码
- 编写JdItemController中的查询接口findJdItemByName
代码截取自个人项目京东价格监控,仅供参考!
/** * 根据商品名在pm_jd_item中搜索商品 * @param itemName * @param startRow * @param pageSize * @return */ @ApiOperation(value="查询商品", notes="查询商品") @RequestMapping(value = "/findJdItemByName", method = {RequestMethod.GET}) public ResponseData<List<JdItem>> findJdItemByName( @ApiParam("用户输入的商品名") @RequestParam(value = "itemName") String itemName, @ApiParam("页码索引(默认为0)") @RequestParam(value = "startRow", required = false, defaultValue = "0") int startRow, @ApiParam("每页的商品数量(默认为10)") @RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize ){ ResponseData<List<JdItem>> responseData = new ResponseData<>(); try { FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery().add(QueryBuilders.matchPhraseQuery("name", itemName), ScoreFunctionBuilders.weightFactorFunction(100)).scoreMode("sum").setMinScore(10); Pageable pageable = new PageRequest(startRow, pageSize); SearchQuery searchQuery = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(functionScoreQueryBuilder).build(); Page<JdItem> jdItems = jdItemRepository.search(searchQuery); // Page分页getTotalPages()返回了应有的页数,临时放在errorMsg传给前端 responseData.jsonFill(1, String.valueOf(jdItems.getTotalPages()), jdItems.getContent()); } catch (Exception e) { e.printStackTrace(); responseData.jsonFill(2, e.getMessage(), null); } return responseData; } } 复制代码
- 运行springboot
调用findJdItemByName接口,得到:
参考
Docker安装ES & Kibana:
Elasticsearch之使用Logstash导入Mysql数据: