通过Spring Data Elasticsearch操作ES

Elasticsearch

        Elasticsearch (ES)是一个基于Lucene构建的开源、分布式、RESTful 接口全文搜索引擎。Elasticsearch 还是一个分布式文档数据库,其中每个字段均是被索引的数据且可被搜索,它能够扩展至数以百计的服务器存储以及处理PB级的数据。它可以在很短的时间内在存储、搜索和分析大量的数据。它通常作为具有复杂搜索场景情况下的核心发动机。es是由java语言编写的

        Elasticsearch就是为高可用和可扩展而生的。可以通过购置性能更强的服务器来完成。

        官网

Elasticsearch:官方分布式搜索和分析引擎 | Elastichttps://www.elastic.co/cn/elasticsearch/

Spring Data

        Spring Data是Spring 的一个子项目。用于简化数据库访问,支持NoSQL和关系数据库存储。其主要目标是使数据库的访问变得方便快捷。

        官网

Spring DataLevel up your Java code and explore what Spring can do for you.https://spring.io/projects/spring-data

Spring Data ElasticSearch

        Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API进行封装。Spring Data为Elasticsearch项目提供集成搜索引擎。Spring Data Elasticsearch POJO的关键功能区域为中心的模型与Elastichsearch交互文档和轻松地编写一个存储库数据访问层。

        官网

Spring Data Elasticsearchhttps://spring.io/projects/spring-data-elasticsearch

代码

        创建maven项目,并引入依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.6.RELEASE</version>
        <relativePath/>
    </parent>

 <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
    </dependencies>

 在resources文件夹下创建application.properties文件

application.properties内容如下

# es 服务地址
elasticsearch.host=部署es服务器的ip
# es 服务端口
elasticsearch.port=9200
# 配置日志级别,开启 debug 日志
logging.level.com.es=debug

创建MainApplication

package com.es;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

创建ElasticSearch配置文件ElasticsearchConfig

package com.es.config;

import lombok.Data;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;

@ConfigurationProperties(prefix = "elasticsearch")
@Configuration
@Data
public class ElasticsearchConfig  extends AbstractElasticsearchConfiguration {

    private String host ;
    private Integer port ;

    @Override
    public RestHighLevelClient elasticsearchClient() {
        RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
        RestHighLevelClient restHighLevelClient = new
                RestHighLevelClient(builder);
        return restHighLevelClient;
    }
}

创建实体类Person

package com.es.DO;
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;

@Data
@Document(indexName = "contact", shards = 3, replicas = 1)
public class Person {

    /**
     * 主键 id
     */
    @Id
    public Long id;

    /**
     * 姓名 name
     */
    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    public String name;

    /**
     * 年龄 age
     */
    @Field(type = FieldType.Integer)
    public int age;

    /**
     * 地址 address
     */
    @Field(type = FieldType.Keyword, index = false)
    public String address;
}

配置Person的Dao类,PersonDao

package com.es.dao;

import com.es.DO.Person;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface PersonDao extends ElasticsearchRepository<Person, Long>{

}

创建测试类SpringDataESIndexTest,测试类跟启动类在同一个包下,不然启动会报错。

package com.es.test;

import com.es.DO.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataESIndexTest {

    //注入 ElasticsearchRestTemplate
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    //创建索引并增加映射配置
    @Test
    public void createIndex(){
        //创建索引,系统初始化会自动创建索引
        System.out.println("创建索引");
    }

    @Test
    public void deleteIndex(){
        //创建索引,系统初始化会自动创建索引
        boolean flg = elasticsearchRestTemplate.deleteIndex(Person.class);
        System.out.println("删除索引 = " + flg);
    }
}

测试

        对索引创建及删除进行测试

        http://IP地址:9200/_cat/indices?v,用浏览器或Postman等工具访问该地址来看结果

        运行createIndex测试方法

         运行deleteIndex测试方法

 文档操作

         新加SpringDataESPersonDaoTest测试类

        新增

    @Autowired
    private PersonDao personDao;
    /**
     * 新增
     */
    @Test
    public void save(){
        Person person = new Person();
        person.setId(1L);
        person.setName("张三");
        person.setAge(21);
        person.setAddress("北京市海淀区");
        personDao.save(person);
    }

测试地址:http://IP地址:9200/contact/_doc/1

 修改

    @Autowired
    private PersonDao personDao;

    //修改
    @Test
    public void update(){
        Person person = new Person();
        person.setId(1L);
        person.setName("张三");
        person.setAge(21);
        person.setAddress("北京市朝阳区");
        personDao.save(person);
    }

 测试地址:http://IP地址:9200/contact/_doc/1

 

根据 id 查询

    @Autowired
    private PersonDao personDao;    
    
    //根据 id 查询
    @Test
    public void findById(){
        Person person = personDao.findById(1L).get();
        System.out.println(person);
    }

打印成功

 打印所有

    @Autowired
    private PersonDao personDao;

    @Test
    public void findAll(){
        Iterable<Person> persons = personDao.findAll();
        for (Person person : persons) {
            System.out.println(person);
        }
    }

 

删除

    @Autowired
    private PersonDao personDao;
    
    @Test
    public void delete(){
        Person person = new Person();
        person.setId(1L);
        personDao.delete(person);
    }

测试地址:http://IP地址:9200/contact/_doc/1

 已删除

 

批量新增

    @Autowired
    private PersonDao personDao;

    //批量新增
    @Test
    public void saveAll(){
        List<Person> personList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Person person = new Person();
            person.setId(Long.valueOf(i));
            person.setName("["+i+"]张三");
            person.setAge(21+i);
            person.setAddress("北京市海淀区");
            personList.add(person);
        }
        personDao.saveAll(personList);
    }

 测试地址:http://ip地址:9200/contact/_search

 

分页查询

    @Autowired
    private PersonDao personDao;
    
    @Test
    public void findByPageable(){
        //设置排序(排序方式,正序还是倒序,排序的 id)
        Sort sort = Sort.by(Sort.Direction.DESC,"id");
        int currentPage=0;//当前页,第一页从 0 开始, 1 表示第二页
        int pageSize = 5;//每页显示多少条
        //设置查询分页
        PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
        //分页查询
        Page<Person> personPage = personDao.findAll(pageRequest);
        for (Person person : personPage.getContent()) {
            System.out.println(person);
        }
    }

查询成功,查出第一页

 完整代码如下

package com.es.test;

import com.es.DO.Person;
import com.es.dao.PersonDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataESPersonDaoTest {
    @Autowired
    private PersonDao personDao;
    /**
     * 新增
     */
    @Test
    public void save(){
        Person person = new Person();
        person.setId(1L);
        person.setName("张三");
        person.setAge(21);
        person.setAddress("北京市海淀区");
        personDao.save(person);
    }
    //POSTMAN, GET http://IP地址:9200/contact/_doc/1

    //修改
    @Test
    public void update(){
        Person person = new Person();
        person.setId(1L);
        person.setName("张三");
        person.setAge(21);
        person.setAddress("北京市朝阳区");
        personDao.save(person);
    }
    //POSTMAN, GET http://IP地址:9200/contact/_doc/1


    //根据 id 查询
    @Test
    public void findById(){
        Person person = personDao.findById(1L).get();
        System.out.println(person);
    }

    @Test
    public void findAll(){
        Iterable<Person> persons = personDao.findAll();
        for (Person person : persons) {
            System.out.println(person);
        }
    }

    //删除
    @Test
    public void delete(){
        Person person = new Person();
        person.setId(1L);
        personDao.delete(person);
    }
    //POSTMAN, GET http://IP地址:9200/contact/_doc/1

    //批量新增
    @Test
    public void saveAll(){
        List<Person> personList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Person person = new Person();
            person.setId(Long.valueOf(i));
            person.setName("["+i+"]张三");
            person.setAge(21+i);
            person.setAddress("北京市海淀区");
            personList.add(person);
        }
        personDao.saveAll(personList);
    }

    //分页查询
    @Test
    public void findByPageable(){
        //设置排序(排序方式,正序还是倒序,排序的 id)
        Sort sort = Sort.by(Sort.Direction.DESC,"id");
        int currentPage=0;//当前页,第一页从 0 开始, 1 表示第二页
        int pageSize = 5;//每页显示多少条
        //设置查询分页
        PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
        //分页查询
        Page<Person> personPage = personDao.findAll(pageRequest);
        for (Person person : personPage.getContent()) {
            System.out.println(person);
        }
    }
}

文档搜索

        新建测试类SpringDataESSearchTest

       termQuery

    @Autowired
    private PersonDao personDao;
    /**
     * term 查询
     * search(termQueryBuilder) 调用搜索方法,参数查询构建器对象
     */
    @Test
    public void termQuery(){
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]张三");
        Iterable<Person> persons = personDao.search(termQueryBuilder);
        for (Person person : persons) {
            System.out.println(person);
        }
    }

 

termQuery加分页

    @Autowired
    private PersonDao personDao;    
    /**
     * term 查询加分页
     */
    @Test
    public void termQueryByPage(){
        int currentPage= 0 ;
        int pageSize = 5;
        //设置查询分页
        PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]张三");
        Iterable<Person> persons =
                personDao.search(termQueryBuilder,pageRequest);
        for (Person person : persons) {
            System.out.println(person);
        }
    }

只有一条name为[8]张三的记录

完整代码如下

package com.es.test;

import com.es.DO.Person;
import com.es.dao.PersonDao;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataESSearchTest {

    @Autowired
    private PersonDao personDao;
    /**
     * term 查询
     * search(termQueryBuilder) 调用搜索方法,参数查询构建器对象
     */
    @Test
    public void termQuery(){
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]张三");
        Iterable<Person> persons = personDao.search(termQueryBuilder);
        for (Person person : persons) {
            System.out.println(person);
        }
    }
    /**
     * term 查询加分页
     */
    @Test
    public void termQueryByPage(){
        int currentPage= 0 ;
        int pageSize = 5;
        //设置查询分页
        PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "[8]张三");
        Iterable<Person> persons =
                personDao.search(termQueryBuilder,pageRequest);
        for (Person person : persons) {
            System.out.println(person);
        }
    }

}
  • 2
    点赞
  • 26
    收藏
  • 打赏
    打赏
  • 0
    评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:博客之星2021 设计师:Hiro_C 返回首页
评论

打赏作者

像向日葵一样~

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值