实例使用SpringBoot结合JestClient组件操作ElasticSearch, 实现全文搜索,精确搜索,区间搜索,创建索引,新增数据,查询数据,批量新增数据,全文搜索,删除索引,删除数据等功能, 由于JestClient版本与ElasticSearch之间的版本有一定的要求, 本文对应的版本见下面:
项目对应的实例代码可以通过【下载实例】按钮获取
开发工具: IntelliJ IDEA 2017, JDK1.8, Maven3.0.2, ElasticSearch-5.6.7(windows版)
【项目包含内容】(见下图):
导入工程后:
JestClient
首先在Maven中添加如下依赖:
<dependency> <groupId>io.searchbox</groupId> <artifactId>jest</artifactId> <version>5.3.3</version> </dependency>
然后编写相关的测试代码。
代码中的注释应该很完整,所以这里就不再对代码过多的讲述了。
import com.alibaba.fastjson.JSON; import com.example.elastic.bean.User; import com.google.gson.Gson; import io.searchbox.client.JestClient; import io.searchbox.client.JestResult; import io.searchbox.core.*; import io.searchbox.indices.CreateIndex; import io.searchbox.indices.DeleteIndex; import io.searchbox.indices.mapping.GetMapping; import io.searchbox.indices.mapping.PutMapping; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.Test; 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.List; @RunWith(SpringRunner.class) @SpringBootTest public class ElasticApplicationTests { private static String indexName = "userindex"; private static String typeName = "user"; @Autowired JestClient jestClient; /** * 创建索引 * @return * @throws Exception */ @Test public void createIndex() throws Exception { JestResult jr = jestClient.execute(new CreateIndex.Builder(indexName).build()); System.out.println(jr.isSucceeded()); } /** * 新增数据 * @return * @throws Exception */ @Test public void insert() throws Exception { User user = new User(1L, "张三", 20, "张三是个Java开发工程师","2018-4-25 11:07:42"); Index index = new Index.Builder(user).index(indexName).type(typeName).build(); try{ JestResult jr = jestClient.execute(index); System.out.println(jr.isSucceeded()); }catch(IOException e){ e.printStackTrace(); } } /** * 查询数据 * @return * @throws Exception */ @Test public void getIndexMapping() throws Exception { GetMapping getMapping = new GetMapping.Builder().addIndex(indexName).addType(typeName).build(); JestResult jr =jestClient.execute(getMapping); System.out.println(jr.getJsonString()); } /** * 向ElasticSearch中批量新增 */ @Test public void insertBatch(){ List<Object> objs = new ArrayList<Object>(); objs.add(new User(1L, "张三三", 20, "张三是个Java开发工程师","2018-4-25 11:07:42")); objs.add(new User(2L, "李四四", 24, "李四是个测试工程师","1980-2-15 19:01:32")); objs.add(new User(3L, "王五五", 25, "王五是个运维工程师","2018-4-24 06:11:32")); boolean result = false; try { Bulk.Builder bulk = new Bulk.Builder().defaultIndex(indexName).defaultType(typeName); for (Object obj : objs) { Index index = new Index.Builder(obj).build(); bulk.addAction(index); } BulkResult br = jestClient.execute(bulk.build()); result = br.isSucceeded(); } catch (Exception e) { e.printStackTrace(); } System.out.println("批量新增:"+result); } /** * 全文搜索 * @param indexName * @param typeName * @param query * @return * @throws Exception */ public static String search(JestClient jestClient,String indexName, String typeName, String query) throws Exception { Search search = new Search.Builder(query).addIndex(indexName).addType(typeName).build(); JestResult jr = jestClient.execute(search); System.out.println("--++"+jr.getJsonString()); System.out.println("--"+jr.getSourceAsObject(User.class)); return jr.getSourceAsString(); } /** * 分页带条件搜索 */ @Test public void serach1() { String query ="工程师"; try { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.queryStringQuery(query)); //分页设置 searchSourceBuilder.from(0).size(2); System.out.println("全文搜索查询语句:"+searchSourceBuilder.toString()); System.out.println("全文搜索返回结果:"+search(jestClient,indexName, typeName, searchSourceBuilder.toString())); } catch (Exception e) { e.printStackTrace(); } } /** * 精确搜索(在指定的属性上精确查询) */ @Test public void serach2() { try { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.termQuery("age", 24)); System.out.println("精确搜索查询语句:"+searchSourceBuilder.toString()); System.out.println("精确搜索返回结果:"+search(jestClient,indexName, typeName, searchSourceBuilder.toString())); } catch (Exception e) { e.printStackTrace(); } } /** * 区间搜索 */ @Test public void serach3() { String createtm="createtm"; String from="2016-6-21 05:11:32"; String to="2018-08-21 06:11:32"; try { SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.rangeQuery(createtm).gte(from).lte(to)); System.out.println("区间搜索语句:"+searchSourceBuilder.toString()); System.out.println("区间搜索返回结果:"+search(jestClient,indexName, typeName, searchSourceBuilder.toString())); } catch (Exception e) { e.printStackTrace(); } } /** * 删除索引 * @return * @throws Exception */ @Test public void deleteIndex() throws Exception{ JestResult jr = jestClient.execute(new DeleteIndex.Builder(indexName).build()); System.out.println(jr.isSucceeded()); } /** * 删除单条数据, 这个id必须是主键才能被删除 * @return * @throws Exception */ @Test public void deleteData()throws Exception{ String id = "1"; DocumentResult dr = jestClient.execute(new Delete.Builder(id).index(indexName).type(typeName).build()); System.out.println(dr.isSucceeded()); }
组合查询与排序
searchSourceBuilder.query(QueryBuilders.rangeQuery(createtm).gte(from).lte(to)).query(QueryBuilders.termQuery("age", 24)); --组合查询
searchSourceBuilder.sort("age", SortOrder.DESC); //排序 --排序
注:测试之前先说明下,本地windows系统安装的是ElasticSearch版本是5.6.7。
测试结果
全文搜索
全文搜索查询语句:{ "from" : 0, "size" : 2, "query" : { "query_string" : { "query" : "工程师" } } } 全文搜索返回结果:{"id":1,"name":"张三","age":20,"description":"张三是个Java开发工程师","createtm":"2018-4-25 11:07:42"},{"id":2,"name":"李四","age":24,"description":"李四是个测试工程师","createtm":"1980-2-15 19:01:32"}
匹配搜索
精确搜索查询语句:{ "query" : { "term" : { "age" : 24 } } } 精确搜索返回结果:{"id":2,"name":"李四","age":24,"description":"李四是个测试工程师","createtm":"1980-2-15 19:01:32"}
时间区间搜索
区间搜索语句:{ "query" : { "range" : { "createtm" : { "from" : "2016-8-21 06:11:32", "to" : "2018-8-21 06:11:32", "include_lower" : true, "include_upper" : true } } } } 区间搜索返回结果:{"id":1,"name":"张三","age":20,"description":"张三是个Java开发工程师","createtm":"2018-4-25 11:07:42"}
新增完数据之后,我们可以上linux的 Kibana中进行相关的查询,查询结果如下:
注:Kibana 是属于ELK中一个开源软件。Kibana可以为 Logstash 和 ElasticSearch 提供的日志分析友好的 Web 界面,可以帮助汇总、分析和搜索重要数据日志。
上述代码中测试返回的结果符合我们的预期。其中关于JestClient只是用到了很少的一部分,更多的使用可以查看JestClient的官方文档。
Windows安装ElasticSearch
1,文件准备
下载地址:
https://www.elastic.co/downloads
选择ElasticSearch相关版本, 然后选择后缀名为ZIP文件进行下载,下载之后进行解压。
2,启动Elasticsearch
进入bin目录下,运行 elasticsearch.bat
然后在浏览上输入: localhost:9200
成功显示一下界面表示成功!
3,安装ES插件
web管理界面head 安装
进入bin目录下,打开cmd,进入dos界面
输入:plugin install mobz/elasticsearch-head
进行下载
成功下载之后,在浏览器输入:http://localhost:9200/_plugin/head/
若显示一下界面,则安装成功!
4,注册服务
进入bin目录下,打开cmd,进入dos界面
依次输入:
service.bat install
service.bat start
成功之后,再输入
services.msc
跳转到Service服务界面,可以直接查看es的运行状态!