spring boot整合elasticsearch

前言

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去查询

keywordsamplejpql snippet
AndfindByLastnameAndFirstname… where x.lastname = ?1 and x.firstname = ?2
OrfindByLastnameOrFirstname …where x.lastname = ?1 or x.firstname = ?2
Is,EqualsfindByFirstname,findByFirstnameIs,findByFirstnameEquals… where x.firstname = 1?
BetweenfindByStartDateBetween… where x.startDate between 1? and ?2
LessThanfindByAgeLessThan… where x.age < ?1
LessThanEqualfindByAgeLessThanEqual… where x.age <= ?1
GreaterThanfindByAgeGreaterThan… where x.age > ?1
GreaterThanEqualfindByAgeGreaterThanEqual… where x.age >= ?1
AfterfindByStartDateAfter… where x.startDate > ?1
BeforefindByStartDateBefore… where x.startDate < ?1
IsNullfindByAgeIsNull… where x.age is null
IsNotNull,NotNullfindByAge(Is)NotNull… where x.age not null
LikefindByFirstnameLike… where x.firstname like ?1
NotLikefindByFirstnameNotLike… where x.firstname not like ?1
StartingWithfindByFirstnameStartingWith… where x.firstname like ?1 (parameter bound with appended %)
EndingWithfindByFirstnameEndingWith… where x.firstname like ?1 (parameter bound with prepended %)
ContainingfindByFirstnameContaining… where x.firstname like ?1 (parameter bound wrapped in %)
OrderByfindByAgeOrderByLastnameDesc… where x.age = ?1 order by x.lastname desc
NotfindByLastnameNot… where x.lastname <> ?1
InfindByAgeIn(Collection ages)… where x.age in ?1
NotInfindByAgeNotIn(Collection age)… where x.age not in ?1
TruefindByActiveTrue()… where x.active = true
FalsefindByActiveFalse()… where x.active = false
IgnoreCasefindByFirstnameIgnoreCase… 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);
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值