Spring Boot与检索(ElasticSearch)

一、ElasticSearch安装环境

  • Linux CentOS 7
  • Docker容器

二、安装步骤

① 下载docker ElasticSearch容器镜像

Docker Hub 镜像下载地址:https://hub.docker.com/

docker pull elasticsearch:7.6.2

② 启动镜像映射

docker run -e ES_JAVA_OPTS="-Xms256m -Xmx256m" -d -p 9200:9200 -p 9300:9300 --name ES01 elasticsearch:7.6.2

注意:根据自己情况来配置 -e ES_JAVA_OPTS="-Xms256m -Xmx256m" 不配置的话,启动会占用你的2G内存,反之,配置的话,启动则根据你配置的内存来分配。

异常:如果启动后,docker容器自动关闭,且无法访问

docker logs -f id[容器id] // 查看启动日志

image-20201002130248299

// 修改 elasticsearch.yml 配置即可解决
// 先查找 elasticsearch.yml
find / -name elasticsearch.yml
vim elasticsearch.yml 路径 

// 在elasticsearch.yml添加下面内容
bootstrap.system_call_filter: false
cluster.initial_master_nodes: ["node-1"]

image-20201002130817493

解决详细方法,请参考博客

  • 运行下面这条指令,并重新启动容器
sysctl -w vm.max_map_count=262144

image-20201002163802716

//重新启动容器
docker start 容器[id]

③ 测试

image-20201002130854558

三、ElasticSearch 基本语法

请参考官方文档进行学习

简单示例演示:使用工具: Postman

image-20201002174516786

发送成功:

image-20201002174717317

注意:如果put 出现 503 错误,需要在配置elasticsearch.yml文件中添加

node.name: node-1

image-20201002174847746

查询

image-20201002180418932

四、整合ElasticSearch

​ springBoot 2.3.0版本及以后版本不支持es查询工具jestClient自动注入

① Jest

2.2 版本

image-20201002203735514

1.引入 jest
<dependency>
    <groupId>io.searchbox</groupId>
    <artifactId>jest</artifactId>
    <version>6.3.1</version>
</dependency>
2. application.yml 配置
spring.elasticsearch.jest.uris=http://192.168.64.129:9200
3.创建bean
public class Article {

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

// get、set省略。。。。
}
4.测试
@Autowired
private JestClient jestClient;
@Test
void contextLoads() {

    Article article = new Article();
    article.setId(1);
    article.setTitle("三国演义");
    article.setAuthor("罗贯中");
    article.setContent("Hello World");

    Object source;
    Index index = new Index.Builder(article).index("sanguo").type("news").build();

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

image-20201002205342622

2.3 版本

由于springboot 2.3.0以后版本不支持自动注入JestClient,如下图我们在yml文件中配置JestClient时会出现划掉的线提示。我们采取手动配置的方式

image-20201002210230272

1.引入 jest
<dependency>
    <groupId>io.searchbox</groupId>
    <artifactId>jest</artifactId>
    <version>6.3.1</version>
</dependency>
2.创建bean
public class Article {

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

// get、set省略。。。。
}
3.手动注入和测试

【jestClient.java】

@Repository
public class jestClient {
    public JestClient getJestCline(){
        JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig
                .Builder("http://192.168.64.129:9200")
                .multiThreaded(true)
                .build());
        return  factory.getObject();
    }
}
@Test
void contextLoads() {
    Article article = new Article();
    article.setId(1);
    article.setTitle("西游记");
    article.setAuthor("吴承恩");
    article.setContent("Hello World");
    Index index = new Index.Builder(article).index("xiyou").type("news").build();

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

image-20201002211338268

4.表达式测试搜索(2.2 和 2.3)

更多操作:https://github.com/searchbox-io/Jest/tree/master/jest

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

    // 执行
    try {
        // 2.2 版本: SearchResult result = jestClient.execute(search);
        // 以下是2.3版本
        SearchResult result = jestClient.getJestCline().execute(search);
        System.out.println(result);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

image-20201002211956011

② springDataElasticSearch

2.2 版本
1.application.yml 配置
spring.data.elasticsearch.cluster-name=elasticsearch
spring.data.elasticsearch.cluster-nodes=118.24.44.169:9301

其他的不过多的赘述了,不在向上面分版本,其他的参考2.3版本,可自行百度。

2.3 版本
1.引入spring-boot-starter-data-elasticsearch
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
2.安装Spring Data 对应版本的ElasticSearch

image-20201002213459314

版本适配说明:https://github.com/spring-projects/spring-data-elasticsearch

如果版本不适配:

1)、升级SpringBoot版本

2)、安装对应版本的ES

3.手动配置Client

image-20201002213831795

现在spring官方推荐我们用High Level REST Client来配置

手动配置如下:

@Configuration
public class ElasticSearchConfig extends AbstractElasticsearchConfiguration {

    @Override
    public RestHighLevelClient elasticsearchClient() {
        ClientConfiguration configuration = ClientConfiguration.builder(
        )
                .connectedTo("192.168.64.129:9200")
                //.withConnectTimeout(Duration.ofSeconds(5))
                //.withSocketTimeout(Duration.ofSeconds(3))
                //.useSsl()
                //.withDefaultHeaders(defaultHeaders)
                //.withBasicAuth(username, password)
                // ... other options
                .build();
        RestHighLevelClient client = RestClients.create(configuration).rest();
        return client;
    }
}
4.创建bean
//6.0版本后,一个index只有一个type了,这里type也被移除。ES默认type为“_doc”
@Document(indexName = "at")
public class Book {
    private Integer id;
    private String bookname;
    private String author;

   //get set 构造函数,toString的得写上,这里太长就删了先
}
5.操作ES有两大类
  1. Elasticsearch Repositories
  2. Elasticsearch Operations

Elasticsearch Repositories

在这里插入图片描述
先用Elasticsearch Repositories,注意接口与接口的关系是extends

@Repository
public interface Bookrepository extends ElasticsearchRepository<Book,Integer> {
    //ElasticsearchCrudRepository 已经过时
    List<Book> findBookById(int i);
}

Elasticsearch Repositories提供了许多关键字,来帮助我们实现方法。我们只需要写抽象方法即可,Elasticsearch Repositories会根据方法名自动我们为我们实现,比如上面findBy就是关键字。我们需要在springboot主配置类上加上注解@EnableElasticsearchRepositories可以使用Elasticsearch提供的的关键字(方法)列表,常用关键字如下

在这里插入图片描述

然后测试一下

@SpringBootTest
class ElasticsearchApplicationTests {

    @Autowired
    Bookrepository bookrepository;

    @Test
    void contextLoads() {
        Book book=new Book(1,"西游记","吴承恩");
        bookrepository.save(book);
    }

    @Test
    void testRepositories(){
        //查询
        //Elasticsearch Repositories提供and,by等一大堆关键字来连接JAVABEAN属性,我们写接口,他自动变成为实现类。
        List<Book> bookById = bookrepository.findBookById(1);
        System.out.println(bookById.get(0));
    }

}

结果
在这里插入图片描述

Elasticsearch Operations

ElasticsearchTemplate是基于Transport client的,Transport client将会再ES8.0中被弃用,用谁不用我多说了吧。
使用Elasticsearch Operations我们需要修改上面的配置类,需要继承AbstractElasticsearchConfiguration,因为基类AbstractElasticsearchConfiguration已经提供了ElasticsearchRestTemplate这个bean
在这里插入图片描述

@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {

    @Override
    public RestHighLevelClient elasticsearchClient() {
        ClientConfiguration configuration = ClientConfiguration.builder(
        )
                .connectedTo("192.168.64.129:9200")//9300会报错
                //.withConnectTimeout(Duration.ofSeconds(5))
                //.withSocketTimeout(Duration.ofSeconds(3))
                //.useSsl()
                //.withDefaultHeaders(defaultHeaders)
                //.withBasicAuth(username, password)
                // ... other options
                .build();
        RestHighLevelClient client = RestClients.create(configuration).rest();
        return client;
    }
}

使用方法

@SpringBootTest
class ElasticsearchApplicationTests {

    @Autowired
    ElasticsearchOperations elasticsearchOperations;

    @Test
    void testSaveByOperations(){
        Book book=new Book(2,"西游记2","吴承恩二世");
        IndexQuery indexQuery= new IndexQueryBuilder()
                .withId(book.getId().toString())
                .withObject(book)
                .build();
        String documentId = elasticsearchOperations.index(indexQuery, IndexCoordinates.of("at"));//返回_id(并非javabean中的ID,而是hits中的)
        System.out.println(documentId);
    }

    @Test
    void testFindByOperations(){
        Book book = elasticsearchOperations.get("2",Book.class,IndexCoordinates.of("at"));//IndexCoordinates的参数为Index
        System.out.println(book);
    }


}

结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值