pom引入
<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>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--jackson -->
<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>
<!-- SpringDataElasticSearch -->
<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>
<!-- spring-test 方便测试 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.4.RELEASE</version>
</dependency>
</dependencies>
applicationContext.xml配置
<?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
">
<!--client客户端配置 -->
<elasticsearch:transport-client id="es_client" cluster-name="my-elasticsearch"
cluster-nodes="127.0.0.1:9301,127.0.0.1:9302,127.0.0.1:9303"/>
<!--配置包扫描器扫描dao接口 -->
<elasticsearch:repositories base-package="com.springdata.respositories"/>
<!-- Elasticsearch 模板对象 -->
<bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<!-- 指向上方client客户端 -->
<constructor-arg name="client" ref="es_client"/>
</bean>
</beans>
实体类配置
<!--这里制定了索引的名称以及type类型 -->
@Document(indexName ="spring_data_index " ,type = "article")
public class Article {
// store:是否存储 index:是否设置分词,默认为true
// analyzer:存储时使用分词器
// searchAnalyzer:查询时使用分词器将查询的字段进行分词
@Id
@Field(store = true,type = FieldType.Long)
private long id;
@Field(store = true,type = FieldType.text,analyzer = "ik_smart",searchAnalyzer = "ik_smart")
private String title;
@Field(store = true,type = FieldType.text,analyzer = "ik_smart",searchAnalyzer = "ik_smart")
private String context;
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 getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
@Override
public String toString() {
return "Article{" +
"id=" + id +
", title='" + title + '\'' +
", context='" + context + '\'' +
'}';
}
}
配置接口
//接口中应该指定实体类以及ID的类型
public interface ArticleRespository extends ElasticsearchRepository<Article,Long> {
//要注意命名规则
//自定义查询
List<Article> findByTitle(String str);
//根据多条件自定义查询
List<Article> findByTitleOrContext(String title,String content);
List<Article> findByTitleOrContext(String title, String content, Pageable pageable);
}
常用步骤
//创建索引
@Autowired
private ArticleRespository articleRespository;
@Autowired
private ElasticsearchTemplate template;
@Test
public void createIndex() throws Exception{
//创建索引,并配置映射关系
template.createIndex(Article.class);
}
//添加Document
@Test
public void addDocument() throws Exception{
//创建一个对象
Article article=new Article();
article.setId(2);
article.setTitle("maven项目对象模型,第二个");
article.setContext("maven是一个开源项目管理工具,第二个");
articleRespository.save(article);
}
//添加多个Document
@Test
public void addDocumentMore() throws Exception{
for(int i =3 ;i<10;i++){
//创建一个对象
Article article=new Article();
article.setId(i);
article.setTitle("maven项目对象模型,第"+i+"个");
article.setContext("maven是一个开源项目管理工具,第"+i+"个");
articleRespository.save(article);
}
}
//删除Document
@Test
public void deleteDocument() throws Exception{
articleRespository.deleteById(1l);
//全部删除
//articleRespository.deleteAll();
}
//修改
@Test
public void updateDocument() throws Exception{
//其实就是添加文档,因为es是基于lucene的,所以修改的原理是先删除再添加
//所以更新文档其实就是添加文档,保持文档与源文档id一致,这样就能覆盖原有文档起到更新的作用
//addDocument();
}
//查询 遍历
@Test
public void searchDocument() throws Exception{
//!!!这不是迭代器
Iterable<Article> articles = articleRespository.findAll();
articles.forEach(article -> System.out.println(article));
}
//查询 byId
@Test
public void searchById() throws Exception {
Optional<Article> optional = articleRespository.findById(3l);
Article article = optional.get();
boolean b = StringUtils.isEmpty(article);
if (!b) {
System.out.println(article);
} else {
System.out.println("无法查询到该对象");
}
}
//自定义查询
@Test
public void searchByTitle(){
List<Article> list = articleRespository.findByTitle("maven");
list.stream().forEach(article -> System.out.println(article));
}
//自定义查询 返回list
@Test
public void searchByTitleOrContent(){
//查询时是分词查询,每个词之间是and关系,所以查询的所有词都应该包含在被查到的对象字段中
List<Article> list = articleRespository.findByTitleOrContext("对象maven", "第3个");
list.stream().forEach(article -> System.out.println(article));
}
//自定义查询并设置分页
@Test
public void searchByTitleOrContentByPage(){
//设置分页信息,默认从第0页开始
Pageable pageable= PageRequest.of(0,3);
List<Article> list = articleRespository.findByTitleOrContext("第二个", "第5个",pageable);
list.stream().forEach(article -> System.out.println(article));
}
//使用原生的查询,查询内容不需要完全匹配
//类似于QueryString
@Test
public void NativeSearchQuery() throws Exception{
//创建一个查询对象
NativeSearchQuery query=new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.queryStringQuery("maven是一个工程构建起").defaultField("title"))
.withPageable(PageRequest.of(0,5))
.withHighlightFields(new HighlightBuilder.Field("title").preTags("<font style='color:red'>").postTags("</font>"))
.build();
List<Article> articles = template.queryForList(query, Article.class);
articles.stream().forEach(article -> System.out.println(article));
}
}