Elasticsearch 是一个分布式、可扩展、实时的搜索与数据分析引擎。 它能从项目一开始就赋予你的数据以搜索、分析和探索的能力,可用于实现全文搜索和实时数据统计。
SpringBoot默认支持两种技术来和ES交互;
1、Jest(默认不生效)
需要导入jest的工具包才生效(io.searchbox.client.JestClient)
2、SpringData ElasticSearch【默认,但是ES版本有可能不合适】
直接上干货:
一 、创建项目 选择Spring Web和ElasticeSearch组件
我们首先使用jest来与ES交互:
1、http://localhost:9200/ 查看ES版本号
2、然后在maven库找到对应的包 https://mvnrepository.com/artifact/io.searchbox/jest
3、将默认springdata ElasticSearch注掉,添加jest路径
4、配置数据源
启动服务没有问题,已连接好
测试一下:
1、创建一个实体
2、编写测试添加索引和内容
@Autowired
JestClient jestClient;
@Test
public void contextLoads() {
//1、给ES中索引一个文档
Article article = new Article();
article.setId(1);
article.setTitle("好消息");
article.setAuthor("aTeng");
article.setContent("Hello World");
//构建一个索引功能 index:索引 type:类型
Index index = new Index.Builder(article).index("xianyu").type("news").build();
try {
//执行
jestClient.execute(index);
} catch (IOException e) {
e.printStackTrace();
}
}
编写搜索查询:json表达式官方指南能找到
https://www.elastic.co/guide/cn/elasticsearch/guide/current/_search_with_query_dsl.html
//测试搜索
@Test
public void search(){
//查找内容里含hello的数据
String json = "{\n" +
" \"query\" : {\n" +
" \"match\" : {\n" +
" \"content\" : \"hello\"\n" +
" }\n" +
" }\n" +
"}";
//构建搜索功能 index:索引 type:类型
Search build = new Search.Builder(json).addIndex("xianyu").addType("news").build();
//执行
try {
SearchResult result = jestClient.execute(build);
System.out.println(result.getJsonString());
} catch (IOException e) {
e.printStackTrace();
}
}
搜索成功!
使用默认SpringData操作ElasticSearch
1、使用默认POM:
2、编辑数据源
name为:
nodes端口改为9300,因为不适用9200
3、重启服务,如果报错的话,可能是版本不合适
解决方法: 1)、升级SpringBoot版本
2)、安装对应版本的ES版本,适配说明:https://github.com/spring-projects/spring-data-elasticsearch
1、创建实体添加注解
@Document(indexName = "xianyu1",type = "book")
2、编写一个 ElasticsearchRepository接口 继承 ElasticsearchRepository
3、直接测试调用
@Test
public void test02(){
Book book = new Book();
book.setId(1);
book.setBookName("颠沛流离");
book.setAuthor("浩叔");
bookRespository.index(book);
}
访问 http://localhost:9200/xianyu1/book/_search 查询xianyu1索引下 book类型下内容含1的数据
http://localhost:9200/xianyu1/book/_search 可以查询xianyu1索引下 book类型下所有数据
我们也可以在BookRespository内自定义查询方式:
官方有示例:https://docs.spring.io/spring-data/elasticsearch/docs/3.0.6.RELEASE/reference/html/
测试
@Test
public void test02(){
// Book book = new Book();
// book.setId(1);
// book.setBookName("颠沛流离");
// book.setAuthor("浩叔");
// bookRespository.index(book);
List<Book> books = bookRespository.findByBookNameLike("离");
System.out.println(books);
}
查询成功
写在最后…其实用习惯了,2个都差不多,不过我感觉默认的更方便一点 - - (主要是代码量少哈哈哈