SpringData--Elasticsearch

本文详细介绍如何使用Spring Data Elasticsearch进行全文搜索引擎的开发,包括引入依赖、配置、实体定义、Repository实现及测试方法。涵盖索引创建、文档添加、查询、删除等操作。

引入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>ES_springData</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <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-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>

</project>

配置

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="esClient" cluster-name="elasticsearch"
                                    cluster-nodes="127.0.0.1:9300"/>
    <!--Dao包扫描-->
    <elasticsearch:repositories base-package="pers.zhang.repository"/>
    <!--模板-->
    <bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client" ref="esClient"/>
    </bean>

</beans>

实体

package pers.zhang.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;

/**
 * @Author: acton_zhang
 * @Date: 2020/3/14 3:30 下午
 * @Version 1.0
 */
@Document(indexName = "article-index", type = "article")
public class Article {

    @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 + '\'' +
                '}';
    }
}

Repository

package pers.zhang.repository;

import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import pers.zhang.entity.Article;


import java.util.List;

/**
 * @Author: acton_zhang
 * @Date: 2020/3/14 3:35 下午
 * @Version 1.0
 */
public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {

    //根据标题进行查询
    List<Article> findByTitle (String title);

    List<Article> findByTitleOrContent (String title, String context);

    List<Article> findByTitleOrContent (String title, String context, Pageable pageable);
}

测试

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 pers.zhang.entity.Article;
import pers.zhang.repository.ArticleRepository;

import java.util.List;
import java.util.Optional;

/**
 * @Author: acton_zhang
 * @Date: 2020/3/14 3:38 下午
 * @Version 1.0
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringDataElasticsearchTest {

    @Autowired
    ArticleRepository articleRepository;

    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;

    @Test
    public void createIndex () {
        //创建索引,配置映射关系
        elasticsearchTemplate.createIndex(Article.class);
    }

    @Test
    public void addDocument () {
        Article article = new Article();
        article.setId(1l);
        article.setTitle("Maven对象模型");
        article.setContent("佛教圣地六块腹肌塑料袋放假了撒");
        articleRepository.save(article);
    }

    @Test
    public void deleteById () {
        articleRepository.deleteById(1l);
    }

    @Test
    //查询所有
    public void findAll () {
        Iterable<Article> all = articleRepository.findAll();
        all.forEach( a -> System.out.println(a));
    }


    @Test
    //根据id查询
    public void findById () {
        Optional<Article> byId = articleRepository.findById(2l);
        System.out.println(byId.get());
    }

    @Test
    public void findByTitle () {
        List<Article> list = articleRepository.findByTitle("对象");
        list.forEach( a -> System.out.println(a));
    }


    @Test
    //多条件查询
    public void findByTitleOrContent () {
        List<Article> list = articleRepository.findByTitleOrContent("ddd", "放假");
        list.forEach( a -> System.out.println(a));
    }

    @Test
    //分页查询
    public void findByPage () {
        Pageable pageable = PageRequest.of(0, 2);
        List<Article> list = articleRepository.findByTitleOrContent("ddd", "放假", pageable);
        list.forEach( a -> System.out.println(a));
    }


    //原生查询
    @Test
    public void testNativeSearchQuery () {
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.queryStringQuery("佛放假").defaultField("content"))
                .withPageable(PageRequest.of(0, 5))
                .build();
        List<Article> articles = elasticsearchTemplate.queryForList(query, Article.class);
        articles.forEach(a -> System.out.println(a));

    }
}
在使用Spring Data Elasticsearch 4.3.x版本时,要使用7.15.2版本的Elasticsearch,也就是说4.3.10版本应搭配Elasticsearch 7.15.2使用[^1]。 ### 集成步骤 若开发人员需要在项目中集成该版本的spring-data-elasticsearch,可按以下操作: #### 引入依赖maven包 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 上述代码展示了如何在Maven项目中引入相关依赖,之后便能够使用Spring-data-es的众多功能来操作Elasticsearch [^3]。 #### 添加配置信息 可通过引入yml文件添加如端口、Elasticsearch地址等配置信息,示例如下: ```yaml server: port: 8016 spring: application: name: search-service elasticsearch: #es的地址 rest: uris: http://192.168.133.152:9200 eureka: client: service-url: defaultZone: http://localhost:8000/eureka ``` ### ES文档名词说明 为了更好地使用spring-data-elasticsearch 4.3.10,需要了解如下ES文档名词: - 索引index:即ES中文档集合,相当于数据库的database。 - 类型type:相当于数据库中的table,其中主键id相当与数据库中的id,是唯一的。向Elasticsearch中存储数据,其实就是向es中的index下面的type中存储json类型的数据 [^3]。 ### 相关仓库地址 spring-data-elasticsearch的github地址为:https://github.com/spring-projects/spring-data-elasticsearch ,开发人员可以在此仓库获取更多相关代码及信息 [^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值