es(七)--Spring Data ElasticSearch 使用

2021-06-10 03:04

阅读:488

标签:lang   enc   工程   图片   string   jar   XML   osi   index   

1.Spring Data ElasticSearch简介

1.1什么是Spring Data

Spring Data是一个用于简化数据库访问,并支持云服务的开源框架。其主要目标是使得对数据的访问变得方便快捷,并支持map-reduce框架和云计算数据服务。 Spring Data可以极大的简化JPA的写法,可以在几乎不用写实现的情况下,实现对数据的访问和操作。除了CRUD外,还包括如分页、排序等一些常用的功能。

Spring Data的官网:http://projects.spring.io/spring-data/

Spring Data常用的功能模块如下
技术图片

技术图片

1.2Spring Data ElasticSearch入门

  • 1.工程搭建

    • 1)创建一个java工程
    • 2)把相关jar包添加到工程中,如果maven工程就添加坐标
    • 3)创建一个spring的配置文件
      1.配置elasticsearch:transport-client
      2.elasticsearch:respositories:包臊面,扫描dao
      3.配置elasticsearchTemplate对象,就是一个bean
  • 2.管理索引库

    • 1)创建一个Entity对象,其实就是一个JavaBean(pojo)映射到一个document上,需要添加一些注解进行标注
    • 2)创建一个Dao,是一个接口,需要继承ElasticSearchRespository接口
    • 3)编写测试代码
  • 3.创建索引

    • 直接使用ElasticsearchTemplate对象的createIndex方法创建索引,并配置映射关系
  • 4.添加文档

    • 1)创建一个Article对象
    • 2)使用ArticleRepository对象,向索引库中添加文档
  • 5.删除文档

    • 直接使用ArticleRepository对象的deleteById方法直接删除
  • 6.查询索引库

    • 直接使用ArticleRespository对象的查询方法
  • 7.自定义查询方法

    • 需要根据SpringDataES的命名规则来命名
    • 如果不设置分页信息,应该在方法中添加一个参数Pageable
    • 如果设置分页信息,应该在方法中添加一个参数Pageable
      Pageable pageable = PageRequest.of(0,15);
    • 注意:设置分页信息,默认是从0页开始
    • 可以对搜索的内容先分词然后再进行查询,每个词之间都是and的关系
  • 8.使用原生的条件查询

    • nativeSearchQuery对象
    • 使用方法:
      1)创建一个NativeSearchQuery对象,设置查询条件:QueryBuilder对象
      2)使用ElasticsearchTemplate对象执行查询
      3)取得查询结果

1)导入Spring Data ElasticSearch坐标

 org.elasticsearch
            elasticsearch
            5.6.8org.elasticsearch.client
            transport
            5.6.8

2)创建applicationContext.xml配置文件,引入elasticsearch命名空间

3)编写实体Article

package com.itheima.domain;

public class Article {

    private Integer id;
    private String title;
    private String content;
    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 + "]";
    }

}

4)编写Dao

package com.itheima.dao;

import com.itheima.domain.Article;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
*Article:dao要对哪一个对象进行操作
*Integer:主键为Integer类型
@Repository
public interface ArticleRepository extends ElasticsearchRepository {

}

5)编写Service

package com.itheima.service;

import com.itheima.domain.Article;

public interface ArticleService {

    public void save(Article article);
    
}
package com.itheima.service.impl;

import com.itheima.dao.ArticleRepository;
import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    public void save(Article article) {
        articleRepository.save(article);
    }

}

6)配置applicationContext.xml

7)配置实体

基于spring data elasticsearch注解配置索引、映射和实体的关系

package com.itheima.domain;

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",type="article")
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;
    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 + "]";
    }

}
其中,注解解释如下:
@Document(indexName="blob3",type="article"):
    indexName:索引的名称(必填项)
    type:索引的类型
@Id:主键的唯一标识
@Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type = FieldType.text)
    index:是否设置分词
    analyzer:存储时使用的分词器
    searchAnalyze:搜索时使用的分词器
    store:是否存储
    type: 数据类型

8)创建测试类SpringDataESTest

package com.itheima.test;

import com.itheima.domain.Article;
import com.itheima.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.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class SpringDataESTest {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private TransportClient client;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**创建索引和映射*/
    @Test
    public void createIndex(){
        //创建索引,并配置映射关系
        elasticsearchTemplate.createIndex(Article.class);
        //配置映射关系
       // elasticsearchTemplate.putMapping(Article.class);//用于只有所以没有映射库的时候
    }

    /**测试保存文档*/
    @Test
    public void saveArticle(){
        Article article = new Article();
        article.setId(100);
        article.setTitle("测试SpringData ElasticSearch");
        article.setContent("Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API 进行封装 \n" +
                "    Spring Data为Elasticsearch Elasticsearch项目提供集成搜索引擎");
        articleService.save(article);
    }

}

3.Spring Data ElasticSearch的常用操作

3.1 增删改查方法测试

package com.itheima.service;

import com.itheima.domain.Article;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

public interface ArticleService {

    //保存
    public void save(Article article);
    //删除
    public void delete(Article article);
    //查询全部
    public Iterable findAll();
    //分页查询
    public Page findAll(Pageable pageable);

}
package com.itheima.service.impl;

import com.itheima.dao.ArticleRepository;
import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;


@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    //更新和保存都用的这个
    public void save(Article article) {
        articleRepository.save(article);
    }
    //通过id删除
    public void deleteById(Article article) {
        articleRepository.deleteById(article);
    }
    //删除包含该字段的
    public void delete(Article article) {
        articleRepository.delete(article);
    }
    //删除所有
    public void deleteAll(Article article) {
        articleRepository.deleteAll(article);
    }

    public Iterable findAll() {
        Iterable iter = articleRepository.findAll();
        iter.forEach(a->sout(a))
        return iter;
    }

    public Article findAllById() {
        Optinal optinal = articleRepository.findById();//optinal为了消除控制异常
        Article article = optinal.get();
        return article;
    }

    public Page findAll(Pageable pageable) {
        return articleRepository.findAll(pageable);
    }
}
package com.itheima.test;

import com.itheima.domain.Article;
import com.itheima.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.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class SpringDataESTest {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private TransportClient client;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**创建索引和映射*/
    @Test
    public void createIndex(){
        elasticsearchTemplate.createIndex(Article.class);
        elasticsearchTemplate.putMapping(Article.class);
    }

    /**测试保存文档*/
    @Test
    public void saveArticle(){
        Article article = new Article();
        article.setId(100);
        article.setTitle("测试SpringData ElasticSearch");
        article.setContent("Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API 进行封装 \n" +
                "    Spring Data为Elasticsearch Elasticsearch项目提供集成搜索引擎");
        articleService.save(article);
    }

    /**测试保存*/
    @Test
    public void save(){
        Article article = new Article();
        article.setId(1001);
        article.setTitle("elasticSearch 3.0版本发布");
        article.setContent("ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");
        articleService.save(article);
    }

    /**测试更新*/
    @Test
    public void update(){
        Article article = new Article();
        article.setId(1001);
        article.setTitle("elasticSearch 3.0版本发布...更新");
        article.setContent("ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口");
        articleService.save(article);
    }

    /**测试删除*/
    @Test
    public void delete(){
        Article article = new Article();
        article.setId(1001);
        articleService.delete(article);
    }

    /**批量插入*/
    @Test
    public void save100(){
        for(int i=1;i

3.2 常用查询命名规则

3.3 查询方法测试

1)dao层实现

package com.itheima.dao;

import com.itheima.domain.Article;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;

public interface ArticleRepository extends ElasticsearchRepository {
    //根据标题查询
    List findByTitle(String condition);
    //根据标题查询(含分页)
    Page findByTitle(String condition, Pageable pageable);
}

2)service层实现

public interface ArticleService {
    //根据标题查询
    List findByTitle(String condition);
    //根据标题查询(含分页)
    Page findByTitle(String condition, Pageable pageable);

    List findByTitleOrContent(String title,Sting content);
}
package com.itheima.service.impl;

import com.itheima.dao.ArticleRepository;
import com.itheima.domain.Article;
import com.itheima.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    //通过标题查询
    public List findByTitle(String condition) {
        return articleRepository.findByTitle(condition);
    }
   
    //分页查询
    public Page findByTitle(String condition, Pageable pageable) {
        return articleRepository.findByTitle(condition,pageable);
    }

    //通过标题或内容查询
    public void testFindByTitleOrContent() throws Exception{
      articleRepository.findByTitleOrContent("maven","商务与投资")
            .forEach(a->sout(a))
    }

}

3)测试代码

package com.itheima.test;

import com.itheima.domain.Article;
import com.itheima.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.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class SpringDataESTest {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private TransportClient client;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**条件查询*/
    @Test
    public void findByTitle(){
        String condition = "版本";
        List articleList = articleService.findByTitle(condition);
        for(Article article:articleList){
            System.out.println(article);
        }
    }

    /**条件分页查询*/
    @Test
    public void findByTitlePage(){
        String condition = "版本";
        Pageable pageable = PageRequest.of(2,10);
        Page page = articleService.findByTitle(condition,pageable);
        for(Article article:page.getContent()){
            System.out.println(article);
        }
    }

}

3.4使用Elasticsearch的原生查询对象进行查询。

分出来的词是的关系

@Test
    public void findByNativeQuery() {
        //创建一个SearchQuery对象
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                //设置查询条件,此处可以使用QueryBuilders创建多种查询
                .withQuery(QueryBuilders.queryStringQuery("备份节点上没有数据").defaultField("title"))
                //还可以设置分页信息
                .withPageable(PageRequest.of(1, 5))
                //创建SearchQuery对象
                .build();


        //使用模板对象执行查询
        elasticsearchTemplate.queryForList(searchQuery, Article.class)
                .forEach(a-> System.out.println(a));
}

es(七)--Spring Data ElasticSearch 使用

标签:lang   enc   工程   图片   string   jar   XML   osi   index   

原文地址:https://www.cnblogs.com/psyduck/p/14467565.html


评论


亲,登录后才可以留言!