ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

Elasticsearch在java中的使用【同步MySQL数据】【模糊查询】【代码】

2022-06-01 15:02:15  阅读:129  来源: 互联网

标签:java org MySQL request 查询 client elasticsearch import Elasticsearch


环境准备

确认已经装好了Elasticsearch【Elasticsearch安装教程 - 博客园

参考教程

参考自 关于在Java中简单的将Mysql中的数据添加到es中并且定时同步更新 - CSDN

参考教程 Java中ElasticSearch的各种查询(普通,模糊,前缀,高亮,聚合,范围) - CSDN

引入依赖

注意!!!

elasticsearch.version 要和自己安装的版本协同

pom依赖代码

<properties>
     <elasticsearch.version>7.15.2</elasticsearch.version>
</properties>

<!-- ElasticSearch模糊查询的依赖 fastJson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.36</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- 不知道这个是什么依赖,但是教程说要要 -->
<!-- 注意以下依赖和 所安装的 Elasticsearch 的版本协同 -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.15.2</version>
    <exclusions>
        <exclusion>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
        </exclusion>
        <exclusion>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<!-- client依赖 -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>7.15.2</version>
</dependency>
<!-- elasticsearch依赖 -->
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.15.2</version>
</dependency>
<!-- 依然不知道这是什么依赖 -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>7.15.2</version>
    <exclusions>
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>

可能遇到的问题

  • fastjson 的版本报红,不下载。

    可能是这个 fastjson 版本和 pom 文件的别的设置冲突了,改一下 fastjson 版本就行

  • pom 文件更新的时候报错 Connot connect

    谁知道这是什么问题啊【应该是我手贱又下载了个JDK导致的自动更新】

    可能是 jdk 环境被自动改了。File -- Setting -- Maven -- Importing -- 查看 JDK for Inporting 的设置是否正确

创建配置类

import org.apache.http.HttpHost;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

// Elasticsearch的配置类【配置es链接】
@Configuration
public class ElasticSearchClientConfig
{
    // 这一段感觉应该是初始化了一个 RequestOptions 变量
    public static final RequestOptions COMMON_OPTIONS;
    static
    {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
        COMMON_OPTIONS = builder.build();
    }

    /**
     * 无账号密码登录
     * @return RestHighLevelClient
     */
    @Bean
    public static RestHighLevelClient restHighLevelClient()
    {
        // 集群配置法
        RestHighLevelClient client = new RestHighLevelClient
                (RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
        return client;
    }
}

将数据库的数据同步到ES

import com.alibaba.fastjson.JSONObject;
import com.placename.general.config.ElasticSearchClientConfig;
import com.placename.general.mapper.PogOfficialInfoMapper;
import com.placename.general.model.domain.PogOfficialInfo;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@EnableScheduling // 定时器
@Component
public class ElasticsearchImpl
{
    @Autowired
    @Resource
    // 这个是要被同步的数据表所对应的Mapper
    private PogOfficialInfoMapper pogOfficialInfoMapper;

    // 定时器注解,每过去5秒执行这个方法
    @Scheduled(cron = "0/5 * * * * ?")
    public void Escalculating()
    {
        // 查询 OfficialInfo 表中的所有数据,待会这些数据全部放在 es 里
        List<PogOfficialInfo> list = pogOfficialInfoMapper.getall();

        // 调用高层对象
        // ElasticSearchClientConfig 为之前写的 Elasticsearch 配置类,restHighLevelClient 是其中的静态方法
        RestHighLevelClient client = ElasticSearchClientConfig.restHighLevelClient();

        // 存储刚刚 list 里获得的对象
        for(PogOfficialInfo temp:list)
        {
            // 创建构造器指定index索引
            IndexRequest indexRequest = new IndexRequest("officialinfo");  // 索引的名字
            indexRequest.id(temp.getId().toString());

            // 创建批量操作的对象
            BulkRequest request = new BulkRequest();

            // 将查询到的数据转化为Json
            indexRequest.source(JSONObject.toJSONString(temp), XContentType.JSON);
            // Json数据放入批量操作对象中
            request.add(indexRequest);

            // 执行操作
            try
            {
                client.bulk(request,ElasticSearchClientConfig.COMMON_OPTIONS);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            System.out.println(temp);
        }
    }
}

Elasticsearch查询示例

GET officialinfo/_search
{
  "query":{
    "match": {
      "content": {
        "query": "疫情 核酸",
        "operator": "or"
      }
    }
  }
}

使用Elasticsearch进行查询

测试类测试

import com.placename.general.model.domain.PogOfficialInfo;
import org.apache.http.HttpHost;
import org.apache.lucene.util.QueryBuilder;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@SpringBootTest
public class ElasticsearchApplicationTest
{
    // 连接客户端
    @Autowired
    RestHighLevelClient client;

    @Test
    public void testClient() throws IOException
    {
        // 初始化客户端
        // 正常操作应该是把这个方法加上 @Before 注解实现比较好
        System.out.println(client);
        HttpHost serverHost = new HttpHost("localhost",9200);
        client = new RestHighLevelClient(RestClient.builder(serverHost));

        /* // 验证索引是否正常 - OK
        // 查询索引信息
        // GetIndexRequest("officialinfo") 中的 officialinfo 为索引名称
        GetIndexRequest request = new GetIndexRequest("officialinfo");
        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);
        // 获取别名
        System.out.println(response.getAliases().toString());
        // 获取默认设置
        System.out.println(response.getDefaultSettings().toString());
        // 获取索引信息
        System.out.println(response.getIndices().toString());
        // 获取映射信息
        System.out.println(response.getMappings().toString());
        */

        /*
        // 验证文档是否正常 - OK
        // 文档查询【查询 id 为 1 的数据】
        // officialinfo 为索引名称
        GetRequest request = new GetRequest().index("officialinfo").id("1");
        GetResponse response = client.get(request,RequestOptions.DEFAULT);
        System.out.println(response);
        */

        // 模糊查询
        // 创建查询request
        // officialinfo 为索引名称
        SearchRequest request = new SearchRequest("officialinfo");
        // 这个request.type() 可能因为 Elasticsearch 版本的问题,已经不用了,如果用的话,会报错
        // 【[types removal] Specifying types in search requests is deprecated."]】
        // request.types("text");
        // 指定查询条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 选择模糊查询匹配的模式是 and 还是 or
        // 也可以不加后面的 .operator(Operator.OR) ,如果不加,就是直接匹配
        builder.query(QueryBuilders.matchQuery("content","防疫 核酸").operator(Operator.OR));
        request.source(builder);
        // 执行查询
        SearchResponse response = client.search(request,RequestOptions.DEFAULT);

        // 结果打印【为什么用 Hit ,需要去看 Elasticsearch 查询的结果,看结果很容易就明白了】
        for(SearchHit hit:response.getHits().getHits())
        {
            System.out.println(hit.getSourceAsMap());
        }

        // 销毁客户端 【同上,理论上应该用 @After 注解实现】
        if(client == null)
        {
            try
            {
                client.close();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}

详细的Elasticsearch的使用我将会再写一个教程,如果有需要,请到我的博客中去寻找阿巴阿巴,这个可以当作初版,或者说代码版

标签:java,org,MySQL,request,查询,client,elasticsearch,import,Elasticsearch
来源: https://www.cnblogs.com/Muhuai/p/16334246.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有