SpringData操作ElasticSearch

使用SpringDataES框架操作ElasticSearch完成crud、分页

SpringData是一个用于简化数据库访问,并支持云服务的开源框架,使用SpringData操作ElasticSearch比用原生Java代码方便许多。Elasticsearch JAVA操作有三种客户端:1、TransportClient 2、JestClient 3、RestClient,本文用TransportClient 操作ES

本文配置了ES集群,通过可视化elasticsearch-head-master在浏览器可直接查看,具体配置方法见另一篇博客:
https://blog.csdn.net/skk_joker/article/details/97486677

首先搭建好框架并配置pom.xml

pom.xml配置如下:注意junit版本必须是4.12以上,不然不兼容

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>5.5.2</version>
    </dependency>

    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>transport</artifactId>
        <version>5.5.2</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-to-slf4j</artifactId>
        <version>2.10.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.9.0</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.25</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>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>2.9.1</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.1</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.5.RELEASE</version>
    </dependency>
</dependencies>

在resourcse中创建配置文件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">
<!--    Elasticsearch JAVA操作有三种客户端:1、TransportClient 2、JestClient 3、RestClient-->
<!--    cluster-name="my-application" 是集群的名称,在集群config目录下的elasticsearch.yml中的集群名称,一定要一致,否则报错-->
<!--    cluster-nodes="127.0.0.1:9301" 是集群的各个分支,有几个写几个,多个的话用逗号隔开:cluster-nodes="127.0.0.1:9301,127.0.0.1:9302,127.0.0.1:9303" 必须和elasticsearch.yml中配置的名称一致-->
<!--    id="ascesClient" id中属性值必须和下面的ref="ascesClient"中的属性值一样,名称随便起,只要一致就行-->
    <elasticsearch:transport-client id="ascesClient" cluster-name="my-application"
                                    cluster-nodes="127.0.0.1:9301"/>
    <elasticsearch:repositories base-package="com.xcy.repositories"/>

<!--    name="client" 可查看源码public ElasticsearchTemplate(Client client)必须和有参构造方法中形参一致-->
<!--    id="elasticsearchTemplate" 通过索引template 操作ES-->
    <bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client" ref="ascesClient"/>
    </bean>
</beans>

构建一个实体类Article

@Document(indexName = "csdn" ,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 + '\'' +
                '}';
    }
}

创建接口

public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {
   
}

测试crud

创建一个索引

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestSpringDataEs{
    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    //创建csdn索引
    @Test
    public void createIndex(){
        elasticsearchTemplate.createIndex(Article.class);
    }
 }

通过可视化elasticsearch-head-master在浏览器查看:
SpringData操作ElasticSearch_第1张图片

追加mapping

//追加mapping
@Test
public void createMapping(){
    elasticsearchTemplate.putMapping(Article.class);
}

SpringData操作ElasticSearch_第2张图片

添加字段

//添加字段
@Test
public void addDocument(){
    Article article = new Article();
    for (int i = 0 ; i <= 100 ; i ++){
        article.setId(i+1l);
        article.setTitle(i+"骁龙855 Plus+120Hz刷新率屏幕");
        article.setContent(i+"凭借着强悍的性能、卓越的游戏体验和丰富的游戏扩展配件");
        articleRepository.save(article);
    }
}

SpringData操作ElasticSearch_第3张图片

通过id删除

//通过id删除
@Test
public void deleteDocumentById(){
    articleRepository.deleteById(1l);
}

删除所有

//删除所有
@Test
public void deleteAllDocument(){
    articleRepository.deleteAll();
}

修改或添加

修改是和添加一样,只不过修改时先把原来的删除再添加上去
//修改是和添加一样,只不过修改时先把原来的删除再添加上去
@Test
public void updateDocumentById(){
    Article article = new Article();
    article.setId(1l);
    article.setTitle("开始吹牛");
    article.setContent("谁相信谁傻");
    articleRepository.save(article);
}

在这里插入图片描述

通过id查询

jdk1.8 中才改动的 springData 中Optional

详情可点击链接https://www.runoob.com/java/java8-optional-class.html

//通过id查询
@Test
public void findDocumentById(){
    Optional<Article> byId = articleRepository.findById(1l);
    Article article = byId.get();
    System.out.println(article);
}

console输出结果:
在这里插入图片描述

查询所有

通过iterator迭代器循环取值
//iterator迭代器
//查询所有
@Test
public void findAllDocument01(){
    Iterable<Article> articles = articleRepository.findAll();
    Iterator<Article> iterator = articles.iterator();
    while (iterator.hasNext()){
        Article article = iterator.next();
        System.out.println(article);
    }
}

SpringData操作ElasticSearch_第4张图片

通过lambda表达式更简洁
//lambda表达式
//查询所有
@Test
public void findAllDocument(){
    Iterable<Article> articles = articleRepository.findAll();
    articles.forEach(a -> System.out.println(a));
}

通过标题的关键字查询

对象可以用中文表示哦!!!!

//通过标题的关键词查询 关键字必须一致才能查询到,像“骁龙”就可以查到,但是“骁龙刷新”就查询不到,虽然“骁龙”和“刷新”都有字段
@Test
public void fandByTitle(){
    List<Article> 骁龙 = articleRepository.findArticleByTitle("骁龙刷新");
    骁龙.stream().forEach(article -> System.out.println(article));
}

没有符合条件的
SpringData操作ElasticSearch_第5张图片
修改查询条件,将“刷新”去掉

@Test
public void fandByTitle(){
    List<Article> 骁龙 = articleRepository.findArticleByTitle("骁龙");
    骁龙.stream().forEach(article -> System.out.println(article));
}

通过console看到可以查询出来
SpringData操作ElasticSearch_第6张图片

通过title and content 查询

//findArticleByTitleAndContent("骁龙", "性能")中的and是指同时满足才能查询出来,默认是只查询出来10条
@Test
public void findByTitleAndContent(){
    List<Article> articleByTitleAndContent = articleRepository.findArticleByTitleAndContent("骁龙", "性能");
    articleByTitleAndContent.stream().forEach(article -> System.out.println(article));
}

SpringData操作ElasticSearch_第7张图片

通过 title or content 查询

//方法中的Or表示只要title和content有一个满足条件就可以被查出来
@Test
public void findByTitleOrContent(){
    List<Article> articleByTitleAndContent = articleRepository.findByTitleOrContent("骁龙", "性放松放松能",pageable);
    articleByTitleAndContent.stream().forEach(article -> System.out.println(article));
}

SpringData操作ElasticSearch_第8张图片

分页查询

使用Pageable进行分页
@Test
public void findByTitleOrContent(){
    Pageable pageable = PageRequest.of(1, 3);
    List<Article> articleByTitleAndContent = articleRepository.findByTitleOrContent("骁龙", "性放松放松能",pageable);
    articleByTitleAndContent.stream().forEach(article -> System.out.println(article));
}

SpringData操作ElasticSearch_第9张图片

使用原生java代码分页
//使用原生代码按照 title 信息查询实现分页
@Test
public void NativeQuery(){
    NativeSearchQuery build = new NativeSearchQueryBuilder()
            .withQuery(QueryBuilders.queryStringQuery("骁龙").defaultField("title"))
            .withPageable(PageRequest.of(2, 5))
            .build();
    List
articleList = elasticsearchTemplate.queryForList(build, Article.class); articleList.stream().forEach(article -> System.out.println(article)); }

SpringData操作ElasticSearch_第10张图片

你可能感兴趣的:(笔记)