ElasticSearch - SpringDataElasticSearch

 

1. Project construction

1. Create a java project;
2. Add related jar packages to the project. If the maven project, add the relevant coordinates:

<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-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.4.RELEASE</version>
        </dependency>

    </dependencies>

3. Create a spring configuration file:

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

    <!--elastic客户对象的配置-->
    <elasticsearch:transport-client id="esClient" cluster-name="elasticsearch" cluster-nodes="127.0.0.1:9300"/>

    <!--配置包扫描器,扫描dao的接口-->
    <elasticsearch:repositories base-package="com.cast.es.repositories"/>

    <!--配置elasticsearchTemplate对象-->
    <bean id="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
        <constructor-arg name="client" ref="esClient"/>
    </bean>

</beans>

 

2. Manage the index library

1. Create an Entity class, which is actually a JavaBean (pojo) mapped to a Document. You need to add some annotations for annotation:

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

// indexName 为关联的索引库的名称      type 为创建索引库的类型
@Document(indexName = "blog", type = "article")
public class Article {

//    配置 mapping 映射
    @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 + '\'' +
                '}';
    }
    
}

2. To create a Dao interface, you need to inherit the ElasticSearchRepository interface:

package com.itheima.es.repositories;

import com.itheima.es.entity.Article;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.List;

// Article 文档       Long 主键类型
public interface ArticleRepository extends ElasticsearchRepository<Article, Long> {

    List<Article> findByTitle(String title);
    List<Article> findByContent(String content);
    List<Article> findByTitleOrContent(String title, String content);
    List<Article> findByTitleOrContent(String title, String content, Pageable pageable);

}

 

3. Code testing

Write test code:

import com.itheima.es.entity.Article;
import com.itheima.es.repositories.ArticleRepository;
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 java.util.List;
import java.util.Optional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")   //获取配置文件
public class SpringDataElasticSearchTest {

    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private ElasticsearchTemplate template;

1. Create an index library

@Test
public void createIndex() throws Exception {
    //创建索引库并配置映射关系
    template.createIndex(Article.class);
    //配置已创建好索引库的映射关系
    //template.putMapping(Article.class);
}

2. Add documents

@Test
public void addDocument() throws Exception {
    //创建一个Article对象
    Article article = new Article();
    article.setId(1l);
    article.setTitle("标题");
    article.setContent("今天天气好晴朗....");
    //把文档写入索引库
    articleRepository.save(article);
}

3. Delete the document

@Test
public void deleteDocumentById() throws Exception {
    //删除指定 id 的文档
    articleRepository.deleteById(1l);
    //全部删除
    //articleRepository.deleteAll();
}

4. Modify the document

***The essence of modifying a document is to delete the original document and recreate a new document, so when you want to modify a document, the operation is the same as adding a document, id is the id of the document to be modified, and the others can be modified directly.

5. Find documents

Query all:

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

Query the specified id

@Test
public void testFindById() throws Exception {
    //查找 id 为 10 的文档 
    Optional<Article> optional = articleRepository.findById(10l);
    Article article = optional.get();
    System.out.println(article);
}

Query specified title

***Query according to the fields split by the ik tokenizer defined in Entity

@Test
public void testFindByTitle() throws Exception {
    List<Article> list = articleRepository.findByTitle("的标题");
    list.stream().forEach(a-> System.out.println(a));
}

Query specified content

***Query according to the fields split by the ik tokenizer defined in Entity

@Test
public void testFindByContent() throws Exception {
    List<Article> list = articleRepository.findByContent("今天天气");
    list.stream().forEach(a-> System.out.println(a));
}

***The above queries show the first 10 data in pagination by default

@Test
public void testNativeSearchQuery() throws Exception {
    //创建一个查询对象
    NativeSearchQuery query = new NativeSearchQueryBuilder()
            .withQuery(QueryBuilders.queryStringQuery("今天天气").defaultField("content"))
            .withPageable(PageRequest.of(0, 5))
            .build();
    //执行查询
    List<Article> articleList = template.queryForList(query, Article.class);
    articleList.forEach(a-> System.out.println(a));
}

Query the specified title field or content Pagination

*** 0 means display the 1st page, 5 means display 5 data per page

@Test
public void testFindByTitleOrContent() throws Exception {
    Pageable pageable = PageRequest.of(0, 5);
    articleRepository.findByTitleOrContent("标题", "天气", pageable).forEach(a-> System.out.println(a));
}

Query the specified title field and content pagination

@Test
public void testFindByTitleAndContent() throws Exception {
    Pageable pageable = PageRequest.of(0, 5);
    articleRepository.findByTitleAndContent("标题","今天天气",pageable).forEach(a-> System.out.println(a));
}

 

 

 


  

Guess you like

Origin blog.csdn.net/weixin_42629433/article/details/83448553