一. 工程搭建
1. 创建一个java工程;
2. 把相关jar包添加到工程中。如果maven工程就添加相关坐标:
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.6.8</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.6.8</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.24</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>3.0.5.RELEASE</version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch.plugin</groupId>
<artifactId>transport-netty4-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
</dependencies>
3. 创建一个spring的配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/elasticsearch
http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd
">
<!--elastic客户对象的配置-->
<elasticsearch:transport-client id="esClient" cluster-name="elasticsearch" cluster-nodes="127.0.0.1:9300"/>
<!--配置包扫描器,扫描dao的接口-->
<elasticsearch:repositories base-package="com.cast.es.repositories"/>
<!--配置elasticsearchTemplate对象-->
<bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="esClient"/>
</bean>
</beans>
二. 管理索引库
1. 创建一个Entity类,其实就是一个JavaBean(pojo)映射到一个Document上. 需要添加一些注解进行标注:
package com.cast.es.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
// indexName 为关联的索引库的名称 type 为创建索引库的类型
@Document(indexName = "blog", type = "article")
public class Article {
// 配置 mapping 映射
@Id
@Field(type = FieldType.Long, store = true)
private long id;
@Field(type = FieldType.text, store = true, analyzer = "ik_smart")
private String title;
@Field(type = FieldType.text, store = true, analyzer = "ik_smart")
private String content;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "Article{" +
"id=" + id +
", title='" + title + '\'' +
", content='" + content + '\'' +
'}';
}
}
2. 创建一个 Dao 接口,需要继承 ElasticSearchRepository 接口:
package com.itheima.es.repositories;
import com.itheima.es.entity.Article;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;
// Article 文档 Long 主键类型
public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {
List<Article> findByTitle(String title);
List<Article> findByContent(String content);
List<Article> findByTitleOrContent(String title, String content);
List<Article> findByTitleOrContent(String title, String content, Pageable pageable);
}
三. 代码测试
编写测试代码:
import com.itheima.es.entity.Article;
import com.itheima.es.repositories.ArticleRepository;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import java.util.Optional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml") //获取配置文件
public class SpringDataElasticSearchTest {
@Autowired
private ArticleRepository articleRepository;
@Autowired
private ElasticsearchTemplate template;
1. 创建索引库
@Test
public void createIndex() throws Exception {
//创建索引库并配置映射关系
template.createIndex(Article.class);
//配置已创建好索引库的映射关系
//template.putMapping(Article.class);
}
2. 添加文档
@Test
public void addDocument() throws Exception {
//创建一个Article对象
Article article = new Article();
article.setId(1l);
article.setTitle("标题");
article.setContent("今天天气好晴朗....");
//把文档写入索引库
articleRepository.save(article);
}
3. 删除文档
@Test
public void deleteDocumentById() throws Exception {
//删除指定 id 的文档
articleRepository.deleteById(1l);
//全部删除
//articleRepository.deleteAll();
}
4. 修改文档
***修改文档的实质就是删除原始文档再重新新建新的文档, 所以要修改某个文档时, 跟添加文档的操作一样, id 为要修改的文档的 id, 其他的直接修改就可以了 .
5. 查找文档
查询所有:
@Test
public void findAll() throws Exception {
//查询所有
Iterable<Article> articles = articleRepository.findAll();
articles.forEach(a-> System.out.println(a));
}
查询指定 id
@Test
public void testFindById() throws Exception {
//查找 id 为 10 的文档
Optional<Article> optional = articleRepository.findById(10l);
Article article = optional.get();
System.out.println(article);
}
查询指定 标题
***根据 Entity 中定义的 ik 分词器拆分的字段来查询
@Test
public void testFindByTitle() throws Exception {
List<Article> list = articleRepository.findByTitle("的标题");
list.stream().forEach(a-> System.out.println(a));
}
查询指定 内容
***根据 Entity 中定义的 ik 分词器拆分的字段来查询
@Test
public void testFindByContent() throws Exception {
List<Article> list = articleRepository.findByContent("今天天气");
list.stream().forEach(a-> System.out.println(a));
}
***以上查询都是默认分页显示前 10 条数据
@Test
public void testNativeSearchQuery() throws Exception {
//创建一个查询对象
NativeSearchQuery query = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.queryStringQuery("今天天气").defaultField("content"))
.withPageable(PageRequest.of(0, 5))
.build();
//执行查询
List<Article> articleList = template.queryForList(query, Article.class);
articleList.forEach(a-> System.out.println(a));
}
查询指定 标题字段 或 内容 分页
*** 0 代表显示第 1 页, 5 代表每页显示 5 条数据
@Test
public void testFindByTitleOrContent() throws Exception {
Pageable pageable = PageRequest.of(0, 5);
articleRepository.findByTitleOrContent("标题", "天气", pageable).forEach(a-> System.out.println(a));
}
查询指定 标题字段 和 内容 分页
@Test
public void testFindByTitleAndContent() throws Exception {
Pageable pageable = PageRequest.of(0, 5);
articleRepository.findByTitleAndContent("标题","今天天气",pageable).forEach(a-> System.out.println(a));
}