Spring Boot学习(二十一)之Spring boot中使用elasticsearch

话不多说直接上代码:先看一下工程目录

pom.xml引入

<?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>com.cicoding</groupId>
    <artifactId>springboot-elasticsearch</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springboot-elasticsearch</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.13.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <!--SpringBoot默认使用SpringData ElasticSearch模块进行操作-->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
        <dependency>
            <groupId>io.searchbox</groupId>
            <artifactId>jest</artifactId>
            <version>5.3.3</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jna</groupId>
            <artifactId>jna</artifactId>
            <version>3.0.9</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

再来看两个bean对象的代码

Article的代码

package com.cicoding.bean;

import io.searchbox.annotations.JestId;

public class Article {

    @JestId
    private Integer id;
    private String author;
    private String title;
    private String content;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

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

Book 代码:

package com.cicoding.bean;

import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName = "cidoingbook",type = "book")
public class Book {
    private Integer id;
    private String author;
    private String bookName;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", author='" + author + '\'' +
                ", bookName='" + bookName + '\'' +
                '}';
    }
}

我们来看我们的接口实现,继承ElasticsearchRepository接口实现,让他帮我们去做

package com.cicoding.repository;
import com.cicoding.bean.Book;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;
public interface BookRepository extends ElasticsearchRepository<Book,Integer> {

    public List<Book> findByBookNameLike(String bookName);
}

激动人心的时刻,看我们的启动类

package com.cicoding;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/*
  SpringBoot默訣:支持兩紳技ボ来和ES交互;1、Jest (默以不生效)
          需要尋入jest的工具包(io. searchbox. client. Jestclient)2、SpringData ElasticSearch [Es版本有可能不合遁1
          版本遁配説明: https://github. com/'spring-projects/spring -data -elasticsearch如果版本不造配: 2.4.d
          1)、升級SpringBoot版本2)、  安装対麼版本的Es
          1)、Client 苧点信息clusterNodes; clusterName2)、ELasticsearchTemplate操作es
          3)、編写一个ElasticsearchRepository的子接口来操作ES;
*/
@SpringBootApplication
public class SpringbootElasticsearchApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootElasticsearchApplication.class, args);
    }
}

我们开始编写测试类来测试我们的代码

package com.cicoding;

import com.cicoding.bean.Article;
import com.cicoding.bean.Book;
import com.cicoding.repository.BookRepository;
import io.searchbox.client.JestClient;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
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.test.context.junit4.SpringRunner;

import java.io.IOException;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootElasticsearchApplicationTests {

    @Autowired
    JestClient jestClient;

    @Autowired
    BookRepository bookRepository;
    @Test
    public void contextLoads() {
        // 给es中添加索引,保存一个文档

        Article article = new Article();
        article.setId(1);
        article.setTitle("测试ES");
        article.setContent("Hello World");
        article.setAuthor("Cicoding");

        // 构建一个索引功能
        Index build = new Index.Builder(article).index("cicoding").type("news").build();

        try {
            jestClient.execute(build);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //测试搜索
    @Test
    public void  search() {
        String json = "{\n" +
                "    \"query\" : {\n" +
                "        \"match\" : {\n" +
                "            \"content\" : \"hello\"\n" +
                "        }\n" +
                "    }\n" +
                "}";
        // 构建搜索功能
        Search build = new Search.Builder(json).addIndex("cicoding").addType("news").build();

        // 执行
        try {
            SearchResult execute = jestClient.execute(build);
            System.out.print(execute.getJsonString());

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

// 测试book接口存入

@Test
    public void  test() {
        Book book = new Book();
        book.setAuthor("cicoding");
        book.setId(2);
        book.setBookName("spring in action!");
        bookRepository.index(book);
    }

    // 测试自己实现方法
    @Test
    public void  test1() {
        for (Book book : bookRepository.findByBookNameLike("action")) {
            System.out.print(book);
        }
    }
}

写入操作查询

搜索执行

springdata es

需要版本匹配,找到spring官网找到springdata然后找到springdata-es

找到打开

https://github.com/spring-projects/spring-data-elasticsearch

版本匹配规则

测试数据都没写,默认为null

测试插入一条数据,则

查询自定义方法查询

//方法实现

public List<Book> findByBookNameLike(String bookName);

@Test

public void test1() {

    for (Book book : bookRepository.findByBookNameLike("action")) {

        System.out.print(book);

    }

}

// 测试自己实现方法

我们看到句action这个索引查询出一条数据

到此完成了es的简单的检索,后面更多文章关注博客哟

看主页进2000人群!

发布了112 篇原创文章 · 获赞 87 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/zhaokejin521/article/details/99093030