SpringBoot-spring-data-elasticsearch7.12.0

Posted 胡安民

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot-spring-data-elasticsearch7.12.0相关的知识,希望对你有一定的参考价值。

maven

注意springboot的版本一定要和elasticsearch和spring-boot-starter-data-elasticsearch的版本匹配,不然就会出现问题

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.1</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.12.0 </version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </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>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

application.yml


server:
  port: 9091
spring:
  elasticsearch:
    rest:
      uris: 106.12.174.220:9200
      connection-timeout: 1s
      read-timeout: 30s

演示

Article

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

//@Document 文档对象 (索引信息、文档类型 )
@Document(indexName="blog3")
public class Article 
    //@Id 文档主键 唯一标识
    @Id
    //@Field 每个文档的字段配置(类型、是否分词、是否存储、分词器 )
    @Field(store=true, index = false,type = FieldType.Integer)
    private Integer id;


    @Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type = FieldType.Text)
    private String title;


    @Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type = FieldType.Text)
    private String content;

    @Field(index=true,store=true,type = FieldType.Double)
    private Double price;

    public Double getPrice() 
        return price;
    

    public void setPrice(Double price) 
        this.price = price;
    

    public Integer getId() 
        return id;
    

    public void setId(Integer 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 + '\\'' +
                ", price=" + price +
                '';
    



ArticleRepository

package com.es.dao;

import com.es.entity.Article;
import org.springframework.data.elasticsearch.annotations.Highlight;
import org.springframework.data.elasticsearch.annotations.HighlightField;
import org.springframework.data.elasticsearch.annotations.HighlightParameters;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface ArticleRepository extends ElasticsearchRepository<Article, Integer> 
    /**
     * 查询内容标题查询
     * @param title 标题
     * @param content 内容
     * @return 返回关键字高亮的结果集
     */
    @Highlight(
            fields = @HighlightField(name = "title"), @HighlightField(name = "content"),
            parameters = @HighlightParameters(preTags = "<span style='color:red'>", postTags = "</span>", numberOfFragments = 0)
    )
    List<SearchHit<Article>> findByTitleOrContent(String title, String content);



ArticleService

package com.es.service;

import com.es.entity.Article;
import org.springframework.data.elasticsearch.core.SearchHit;

import java.util.List;

public interface ArticleService 
    //保存和修改
    void save(Article article);
    //查询id
    Article findById(Integer id);
    //删除指定ID数据
    void   deleteById(Integer id);

    long count();
    boolean existsById(Integer id);

    List<SearchHit<Article>> findByTitleOrContent(String title, String content);




ArticleServiceImpl

package com.es.service.impl;

import com.es.dao.ArticleRepository;
import com.es.entity.Article;
import com.es.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService 

    @Autowired
    private ArticleRepository articleRepository;
    @Override
    public void save(Article article) 
       articleRepository.save(article);
    

    @Override
    public Article findById(Integer id) 
        Article article = articleRepository.findById(id).orElse(new Article());
        return  article;
    

    @Override
    public void deleteById(Integer id) 
        articleRepository.deleteById(id);
    

    @Override
    public long count() 
        return articleRepository.count();
    

    @Override
    public boolean existsById(Integer id) 
        return articleRepository.existsById(id);
    

    @Override
    public List<SearchHit<Article>> findByTitleOrContent(String title, String content) 
        return articleRepository.findByTitleOrContent(title,content);
    


ESApplication

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

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


SpringDataESTest

package com.es;

import com.es.entity.Article;
import com.es.service.ArticleService;
import org.elasticsearch.client.transport.TransportClient;
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.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.List;

@RunWith(SpringRunner.class)

@SpringBootTest(classes = ESApplication.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class SpringDataESTest 

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    /**创建索引和映射*/
    @org.junit.Test
    public void createIndex()

//        elasticsearchTemplate.createIndex(Article.class);
//        elasticsearchTemplate.putMapping(Article.class);
    

    /**添加文档或者修改文档(以id为准)*/
    @Test
    public void saveArticle()
        Article article = new Article();
        article.setId(102);
        article.setTitle("xxxxxxSpringData ElasticSearch-------");
        article.setContent("Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API 进行封装 \\n" +
                "    Spring Data为Elasticsearch Elasticsearch项目提供集成搜索引擎");
        articleService.save(article);
    
    @Test
    public void findById()
        Article byId = articleService.findById(100);
        System.out.println(byId);
    
    @Test
    public void deleteById()
       articleService.deleteById(100);

    
    @Test
    public void count()
        long count = articleService.count();
        System.out.println(count);
        
    @Test
    public void existsById()
        boolean b = articleService.existsById(102);

        System.out.println(b);
    
    @Test
    public void findByTitleOrContent()
        List<SearchHit<Article>> byTitleOrContent = articleService.findByTitleOrContent("xxxxxxSpringData","elasticSearch");
        for (SearchHit<Article> articleSearchHit : byTitleOrContent) 
            List<String> title = articleSearchHit.getHighlightField("title");
            System.out.println(title);
            List<String> content = articleSearchHit.getHighlightField("content");
            System.out.println(content);

        
    



自定义查询方式

关键字解释方法
and根据Field1和Field2获得数据findByTitleAndContent(String title,String content);
or根据Field1或Field2获得数据findByTitleOrContent(String title,String content);
is根据Field获得数据findByTitle(String title);
not根据Field获得相反数据findByTitleNot(String title)
between获得指定范围的数据findByPriceBetween(double price1, double price2);
lessThanEqual获得小于等于指定值的数据findByPriceLessThan(double price);
GreaterThanEqual获得大于等于指定值的数据findByPriceGreaterThan(double price);
BeforefindByPriceBefore
AfterfindByPriceAfter
Like比较相识的数据findByNameLike
StartingWith以xx开头的 数据findByNameStartingWith(String Name);
EndingWith以xx结尾的 数据findByNameEndingWith(String Name);
Contains/Containing包含的 数据findByNameContaining(String Name);
In多 值匹配findByNameIn(Collection<String>names)
NotIn多 值 不匹配findByNameNotIn(Collection<String>names)
OrderBy排序 后的数据findByxxxxxOrderByNameDesc(String xxx );

比如: findByTitleAndContent 如果你的表中没有title字段和content那么就无效这个方法
列: List<Article> findByTitleAndContent(String title,String content);

获得指定范围的数据: 方法 findByPriceBetween
列: List<Article> findByPriceBetween(double

以上是关于SpringBoot-spring-data-elasticsearch7.12.0的主要内容,如果未能解决你的问题,请参考以下文章