前言
es版本:6.6.1
spring boot 2.0.1
1、引入依赖
直接在子模块里面引入spring-data-es的依赖即可
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2、application.properties配置
加入下面这段配置es就会链接上
spring.data.elasticsearch.cluster-nodes=localhost:9300
3、Elasticsearch的elasticsearch.yml中的配置新增信息如下:
http.cors.enabled: true
http.cors.allow-origin: "*"
node.master: true
node.data: true
4、添加es测试类
4.1、新增索引
实体类:
import lombok.Data;
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;
@Document(indexName = "account",type = "user", shards = 1, replicas = 0)
@Data
public class User {
@Id
private String id;
@Field(type = FieldType.text, analyzer = "ik_max_word")
private String name; //姓名
@Field(type = FieldType.keyword)
private String job;// 职称
@Field(type = FieldType.keyword)
private String hob; // 爱好
@Field(type = FieldType.Double)
private Double age; // 年龄
@Field(index = false, type = FieldType.keyword)
private String images;
}
测试类:
import com.clockbone.esentity.User;
import com.clockbone.web.AbstratApplicationBaseBootTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
public class createTest extends AbstratApplicationBaseBootTest{
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Test
public void createIndexTest(){
elasticsearchTemplate.createIndex(User.class);
}
}
运行如果你添加redis的引入,可能会报如下错误
Failed to instantiate [org.elasticsearch.client.transport.TransportClient]: Factory method ‘elasticsearchClient’ threw exception; nested exception is java.lang.IllegalStateException: availableProcessors is already set to [4], rejecting [4]
查找解决方法在spring boot的启动类main方法中添加如下代码:
System.setProperty("es.set.netty.runtime.available.processors","false");
我添加后还是依旧报错,所以直接把spring-data-redis的依赖去掉了,重新跑测试类就成功了,后面这个错误再仔细查看。
打看cmd运行curl -X GET localhost:9200/_cat/indices?v
查看所有索引返回如下:
user索引已经创建成功。
4.2删除索引
根据类名删除
@Test
public void createIndexTest(){
elasticsearchTemplate.deleteIndex(User.class);
}
4.3新增文档数据
spring boot启动类添加注解
@EnableElasticsearchRepositories("com.clockbone.esrepository")
UserRepository 接口
package com.clockbone.esrepository;
import com.clockbone.esentity.User;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface UserRepository extends ElasticsearchRepository<User, String> {
}
测试类
import com.clockbone.esentity.User;
import com.clockbone.esrepository.UserRepository;
import com.clockbone.web.AbstratApplicationBaseBootTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
public class userRepositoryTest extends AbstratApplicationBaseBootTest{
@Autowired
private UserRepository userRepository;
@Test
public void insertTest(){
User user = User.builder().age(30D).hob("游泳").images("http://").name("张三").id("1").build();
userRepository.save(user);
}
}
运行成功后,查看es数据curl localhost:9200/account/user/1?pretty=true
,返回
4.4 修改文档数据
新增和修改是一个接口,如果id存在那么是修改,如果id不存在那么就是新增
4.5 查询
查询所有:
@Test
public void queryTest(){
//按年龄排序返回
Iterable<User> iterable = userRepository.findAll(Sort.by("age").ascending());
for(User eachUser : iterable){
System.out.println(eachUser);
}
}
返回:
4.6 自定义方法
根据spring data提供的方法名自动实现功能,如需符合sping data定义的规定即可,比如:findByName,就会根据name去查询
keyword | sample | jpql snippet |
---|---|---|
And | findByLastnameAndFirstname | … where x.lastname = ?1 and x.firstname = ?2 |
Or | findByLastnameOrFirstname … | where x.lastname = ?1 or x.firstname = ?2 |
Is,Equals | findByFirstname,findByFirstnameIs,findByFirstnameEquals | … where x.firstname = 1? |
Between | findByStartDateBetween | … where x.startDate between 1? and ?2 |
LessThan | findByAgeLessThan | … where x.age < ?1 |
LessThanEqual | findByAgeLessThanEqual | … where x.age <= ?1 |
GreaterThan | findByAgeGreaterThan | … where x.age > ?1 |
GreaterThanEqual | findByAgeGreaterThanEqual | … where x.age >= ?1 |
After | findByStartDateAfter | … where x.startDate > ?1 |
Before | findByStartDateBefore | … where x.startDate < ?1 |
IsNull | findByAgeIsNull | … where x.age is null |
IsNotNull,NotNull | findByAge(Is)NotNull | … where x.age not null |
Like | findByFirstnameLike | … where x.firstname like ?1 |
NotLike | findByFirstnameNotLike | … where x.firstname not like ?1 |
StartingWith | findByFirstnameStartingWith | … where x.firstname like ?1 (parameter bound with appended %) |
EndingWith | findByFirstnameEndingWith | … where x.firstname like ?1 (parameter bound with prepended %) |
Containing | findByFirstnameContaining | … where x.firstname like ?1 (parameter bound wrapped in %) |
OrderBy | findByAgeOrderByLastnameDesc | … where x.age = ?1 order by x.lastname desc |
Not | findByLastnameNot | … where x.lastname <> ?1 |
In | findByAgeIn(Collection ages) | … where x.age in ?1 |
NotIn | findByAgeNotIn(Collection age) | … where x.age not in ?1 |
True | findByActiveTrue() | … where x.active = true |
False | findByActiveFalse() | … where x.active = false |
IgnoreCase | findByFirstnameIgnoreCase | … where UPPER(x.firstame) = UPPER(?1) |
添加UserRepository方法根据年龄区间查询数据
public interface UserRepository extends ElasticsearchRepository<User, String> {
List<User> findByAgeBetween(double age1, double age2);
}
返回:
4.7 自定义查询
@Test
public void matchTest(){
// 构建查询条件
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
// 添加基本分词查询
queryBuilder.withQuery(QueryBuilders.matchQuery("name", "张三"));
// 搜索,获取结果
Page<User> users = this.userRepository.search(queryBuilder.build());
// 总条数
long total = users.getTotalElements();
System.out.println("total = " + total);
for (User each : users) {
System.out.println(each);
}
}
运行结果:
多条件:
queryBuilder.withQuery(
QueryBuilders.boolQuery()
.must(QueryBuilders.matchQuery("name", "张三"))
.must(QueryBuilders.matchQuery("name", "张三"))
);
4.7 分页
@Test
public void searchByPage(){
// 构建查询条件
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
// 添加基本分词查询
queryBuilder.withQuery(QueryBuilders.termQuery("age", "30"));
// 分页:
int page = 0;
int size = 10;
queryBuilder.withPageable(PageRequest.of(page,size));
// 搜索,获取结果
Page<User> uspage = userRepository.search(queryBuilder.build());
System.out.println(uspage);
// 总条数
long total = uspage.getTotalElements();
System.out.println("总条数 = " + total);
// 总页数
System.out.println("总页数 = " + uspage.getTotalPages());
// 当前页
System.out.println("当前页:" + uspage.getNumber());
// 每页大小
System.out.println("每页大小:" + uspage.getSize());
for (User user : uspage) {
System.out.println(user);
}
}