技术博客
惊喜好礼享不停
技术博客
SpringBoot与Elasticsearch集成指南:从基础到进阶

SpringBoot与Elasticsearch集成指南:从基础到进阶

作者: 万维易源
2024-11-18
SpringBootElasticsearches-head跨域配置索引操作

摘要

本文详细介绍了如何在SpringBoot项目中集成Elasticsearch(ES),并进行基本的操作。首先,通过学习Linux基础命令,用户可以进入编辑模式进行文件编辑,编辑完成后退出并保存文件。接着,文章讲解了如何使用Elasticsearch进行索引的创建和文档的增删改查等操作。为了方便操作,本文推荐使用es-head作为图形化工具。需要注意的是,高亮显示功能在ES7.9.x版本中才被引入,而在ES7.7版本中可能会出现报错。此外,由于前后端分离的架构,直接输入ES地址无法连接,需要进行跨域配置。

关键词

SpringBoot, Elasticsearch, es-head, 跨域配置, 索引操作

一、环境准备与基础设置

1.1 SpringBoot与Elasticsearch环境搭建

在现代的软件开发中,SpringBoot因其简洁和高效的特点而广受欢迎。而Elasticsearch(ES)则以其强大的搜索和分析能力,在大数据处理领域占据一席之地。将这两者结合,可以为应用程序提供高效的搜索和数据处理能力。以下是详细的环境搭建步骤:

  1. 添加依赖:首先,在SpringBoot项目的pom.xml文件中添加Elasticsearch的依赖。这可以通过Maven或Gradle来实现。例如,使用Maven时,可以在pom.xml中添加以下依赖:
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
    
  2. 配置Elasticsearch:在application.propertiesapplication.yml文件中配置Elasticsearch的连接信息。例如:
    spring:
      elasticsearch:
        rest:
          uris: http://localhost:9200
    
  3. 启动Elasticsearch服务:确保Elasticsearch服务已经启动并运行在指定的端口上。可以通过命令行启动Elasticsearch:
    bin/elasticsearch
    
  4. 测试连接:在SpringBoot应用中编写一个简单的测试类,验证是否能够成功连接到Elasticsearch。例如:
    @SpringBootTest
    public class ElasticsearchTest {
        @Autowired
        private RestHighLevelClient client;
    
        @Test
        public void testConnection() throws IOException {
            Request request = new Request("GET", "/");
            Response response = client.performRequest(request);
            System.out.println(response.getStatusLine().getStatusCode());
        }
    }
    

1.2 Linux基础命令与文件编辑

在Linux环境中,掌握一些基础命令对于文件编辑和系统管理至关重要。以下是一些常用的Linux命令及其用途:

  1. 进入编辑模式:使用vinano编辑器打开文件。例如,使用vi编辑器打开一个文件:
    vi filename.txt
    
  2. 编辑文件:在vi编辑器中,按i键进入插入模式,可以开始编辑文件。编辑完成后,按Esc键退出插入模式,然后输入:wq保存并退出。
  3. 查看文件内容:使用cat命令查看文件内容:
    cat filename.txt
    
  4. 查找文件:使用find命令查找文件。例如,查找当前目录及其子目录下的所有.txt文件:
    find . -name "*.txt"
    
  5. 复制、移动和删除文件:使用cpmvrm命令进行文件操作。例如,复制文件:
    cp source.txt destination.txt
    

1.3 Elasticsearch的安装与配置

Elasticsearch的安装和配置相对简单,但需要一些基本的系统管理知识。以下是详细的安装和配置步骤:

  1. 下载Elasticsearch:从Elastic官网下载最新版本的Elasticsearch。例如,下载7.9.0版本:
    wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-7.9.0-linux-x86_64.tar.gz
    
  2. 解压文件:使用tar命令解压下载的文件:
    tar -xzf elasticsearch-7.9.0-linux-x86_64.tar.gz
    
  3. 配置Elasticsearch:进入解压后的目录,编辑config/elasticsearch.yml文件,配置Elasticsearch的基本参数。例如,设置集群名称和节点名称:
    cluster.name: my-cluster
    node.name: node-1
    
  4. 启动Elasticsearch:在Elasticsearch目录下,使用以下命令启动Elasticsearch服务:
    bin/elasticsearch
    
  5. 验证安装:打开浏览器,访问http://localhost:9200,如果看到类似以下的JSON响应,说明Elasticsearch已成功启动:
    {
      "name" : "node-1",
      "cluster_name" : "my-cluster",
      "cluster_uuid" : "uXjYzWQdRkGhIJKLmNOpQw",
      "version" : {
        "number" : "7.9.0",
        "build_flavor" : "default",
        "build_type" : "tar",
        "build_hash" : "a479a2a",
        "build_date" : "2020-08-11T21:36:46.119083Z",
        "build_snapshot" : false,
        "lucene_version" : "8.6.0",
        "minimum_wire_compatibility_version" : "6.8.0",
        "minimum_index_compatibility_version" : "6.0.0-beta1"
      },
      "tagline" : "You Know, for Search"
    }
    

通过以上步骤,您可以在SpringBoot项目中成功集成Elasticsearch,并进行基本的操作。接下来,我们将进一步探讨如何使用Elasticsearch进行索引的创建和文档的增删改查等操作。

二、Elasticsearch索引与文档操作

2.1 Elasticsearch索引的创建与管理

在Elasticsearch中,索引是存储相关数据的逻辑空间。创建和管理索引是使用Elasticsearch进行数据操作的基础。以下是如何在SpringBoot项目中创建和管理Elasticsearch索引的详细步骤:

  1. 创建索引:在SpringBoot中,可以通过RestHighLevelClient对象创建索引。首先,定义索引的映射(mapping),然后发送请求创建索引。例如:
    @Service
    public class ElasticsearchService {
        @Autowired
        private RestHighLevelClient client;
    
        public void createIndex(String indexName) throws IOException {
            CreateIndexRequest request = new CreateIndexRequest(indexName);
            request.mapping("{\n" +
                    "  \"properties\": {\n" +
                    "    \"title\": {\n" +
                    "      \"type\": \"text\"\n" +
                    "    },\n" +
                    "    \"content\": {\n" +
                    "      \"type\": \"text\"\n" +
                    "    }\n" +
                    "  }\n" +
                    "}", XContentType.JSON);
            client.indices().create(request, RequestOptions.DEFAULT);
        }
    }
    
  2. 检查索引是否存在:在创建索引之前,最好先检查该索引是否已经存在,以避免重复创建。可以通过GetIndexRequest对象来实现:
    public boolean indexExists(String indexName) throws IOException {
        GetIndexRequest request = new GetIndexRequest(indexName);
        return client.indices().exists(request, RequestOptions.DEFAULT);
    }
    
  3. 删除索引:如果需要删除某个索引,可以使用DeleteIndexRequest对象:
    public void deleteIndex(String indexName) throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(indexName);
        client.indices().delete(request, RequestOptions.DEFAULT);
    }
    
  4. 更新索引映射:在某些情况下,可能需要更新索引的映射。可以通过PutMappingRequest对象来实现:
    public void updateMapping(String indexName) throws IOException {
        PutMappingRequest request = new PutMappingRequest(indexName);
        request.source("{\n" +
                "  \"properties\": {\n" +
                "    \"newField\": {\n" +
                "      \"type\": \"keyword\"\n" +
                "    }\n" +
                "  }\n" +
                "}", XContentType.JSON);
        client.indices().putMapping(request, RequestOptions.DEFAULT);
    }
    

2.2 文档的基本操作:增删改查

在Elasticsearch中,文档是存储在索引中的基本单位。以下是如何在SpringBoot项目中进行文档的增删改查操作:

  1. 添加文档:通过IndexRequest对象可以向索引中添加文档。例如:
    public void addDocument(String indexName, String id, Map<String, Object> document) throws IOException {
        IndexRequest request = new IndexRequest(indexName).id(id).source(document);
        client.index(request, RequestOptions.DEFAULT);
    }
    
  2. 查询文档:通过SearchRequest对象可以查询索引中的文档。例如,查询所有文档:
    public List<Map<String, Object>> searchDocuments(String indexName) throws IOException {
        SearchRequest request = new SearchRequest(indexName);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        request.source(sourceBuilder);
    
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        List<Map<String, Object>> documents = new ArrayList<>();
        for (SearchHit hit : response.getHits()) {
            documents.add(hit.getSourceAsMap());
        }
        return documents;
    }
    
  3. 更新文档:通过UpdateRequest对象可以更新索引中的文档。例如:
    public void updateDocument(String indexName, String id, Map<String, Object> updates) throws IOException {
        UpdateRequest request = new UpdateRequest(indexName, id).doc(updates);
        client.update(request, RequestOptions.DEFAULT);
    }
    
  4. 删除文档:通过DeleteRequest对象可以删除索引中的文档。例如:
    public void deleteDocument(String indexName, String id) throws IOException {
        DeleteRequest request = new DeleteRequest(indexName, id);
        client.delete(request, RequestOptions.DEFAULT);
    }
    

2.3 高亮显示功能的使用与注意事项

高亮显示功能可以帮助用户在搜索结果中快速找到匹配的关键字。在Elasticsearch 7.9.x版本中,高亮显示功能得到了增强,但在7.7版本中可能会出现报错。以下是如何在SpringBoot项目中使用高亮显示功能:

  1. 启用高亮显示:在查询请求中启用高亮显示功能。例如:
    public List<Map<String, Object>> searchWithHighlight(String indexName, String query) throws IOException {
        SearchRequest request = new SearchRequest(indexName);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchQuery("content", query));
    
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("content");
        highlightBuilder.preTags("<span style='background-color: yellow;'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);
    
        request.source(sourceBuilder);
    
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        List<Map<String, Object>> documents = new ArrayList<>();
        for (SearchHit hit : response.getHits()) {
            Map<String, Object> source = hit.getSourceAsMap();
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField contentField = highlightFields.get("content");
            if (contentField != null) {
                Text[] fragments = contentField.fragments();
                String highlightedContent = "";
                for (Text fragment : fragments) {
                    highlightedContent += fragment.string();
                }
                source.put("content", highlightedContent);
            }
            documents.add(source);
        }
        return documents;
    }
    
  2. 注意事项
    • 版本兼容性:确保使用的Elasticsearch版本支持高亮显示功能。在7.7版本中,高亮显示功能可能会出现报错,建议使用7.9.x或更高版本。
    • 性能影响:高亮显示功能会增加查询的复杂度,可能会影响查询性能。在生产环境中,应根据实际需求权衡是否启用高亮显示。
    • 标签安全:在生成高亮显示的HTML标签时,确保标签的安全性,防止XSS攻击。

通过以上步骤,您可以在SpringBoot项目中有效地使用Elasticsearch进行索引的创建和管理,以及文档的增删改查操作。同时,高亮显示功能的使用可以提升用户体验,但需要注意版本兼容性和性能影响。希望这些内容对您的项目有所帮助。

三、Elasticsearch操作工具与跨域配置

3.1 es-head工具的安装与使用

在Elasticsearch的日常管理和操作中,使用图形化工具可以大大提升效率和便捷性。es-head是一个非常流行的Elasticsearch图形化操作工具,它提供了直观的界面,使得索引管理和文档操作变得更加简单。以下是es-head的安装和使用步骤:

  1. 安装Node.js:es-head基于Node.js开发,因此首先需要在系统中安装Node.js。可以通过以下命令安装Node.js:
    curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
    sudo apt-get install -y nodejs
    
  2. 克隆es-head仓库:从GitHub上克隆es-head的源代码仓库:
    git clone https://github.com/mobz/elasticsearch-head.git
    
  3. 安装依赖:进入克隆的目录,安装所需的npm依赖:
    cd elasticsearch-head
    npm install
    
  4. 启动es-head:使用以下命令启动es-head服务:
    npm run start
    

    启动后,es-head默认会在http://localhost:9100上运行。打开浏览器,访问该地址即可看到es-head的界面。
  5. 连接Elasticsearch:在es-head的界面上,点击“Connect to server”按钮,输入Elasticsearch的地址(例如http://localhost:9200),点击“Connect”按钮即可连接到Elasticsearch。

通过es-head,用户可以轻松地进行索引的创建、删除、查看文档等操作,极大地简化了Elasticsearch的管理过程。

3.2 Kibana的图形化操作简介

Kibana是Elasticsearch官方提供的图形化操作工具,它不仅提供了丰富的可视化功能,还支持索引管理和文档操作。Kibana的界面友好且功能强大,是Elasticsearch用户的首选工具。以下是Kibana的基本使用方法:

  1. 安装Kibana:从Elastic官网下载Kibana的安装包。例如,下载7.9.0版本:
    wget https://artifacts.elastic.co/downloads/kibana/kibana-7.9.0-linux-x86_64.tar.gz
    
  2. 解压文件:使用tar命令解压下载的文件:
    tar -xzf kibana-7.9.0-linux-x86_64.tar.gz
    
  3. 配置Kibana:进入解压后的目录,编辑config/kibana.yml文件,配置Kibana连接Elasticsearch的地址。例如:
    server.host: "0.0.0.0"
    elasticsearch.hosts: ["http://localhost:9200"]
    
  4. 启动Kibana:在Kibana目录下,使用以下命令启动Kibana服务:
    bin/kibana
    
  5. 访问Kibana:打开浏览器,访问http://localhost:5601,即可看到Kibana的界面。

在Kibana中,用户可以进行索引的管理、文档的查询和修改,还可以创建各种图表和仪表板,实现数据的可视化展示。Kibana的强大功能使得Elasticsearch的数据分析和管理变得更加直观和高效。

3.3 Elasticsearch与前端跨域配置详解

在现代Web应用中,前后端分离的架构越来越普遍。在这种架构下,前端应用通常运行在不同的域名或端口上,而Elasticsearch服务则运行在另一个域名或端口上。为了使前端应用能够顺利连接到Elasticsearch,需要进行跨域配置。以下是详细的跨域配置步骤:

  1. 修改Elasticsearch配置文件:编辑Elasticsearch的config/elasticsearch.yml文件,添加以下配置项:
    http.cors.enabled: true
    http.cors.allow-origin: "*"
    http.cors.allow-methods: "GET, POST, PUT, DELETE, OPTIONS"
    http.cors.allow-headers: "X-Requested-With, Content-Type, Content-Length, Authorization"
    

    其中,http.cors.enabled用于启用跨域支持,http.cors.allow-origin用于指定允许跨域访问的源,http.cors.allow-methods用于指定允许的HTTP方法,http.cors.allow-headers用于指定允许的HTTP头。
  2. 重启Elasticsearch服务:保存配置文件后,重启Elasticsearch服务以使配置生效:
    bin/elasticsearch
    
  3. 前端配置:在前端应用中,配置请求的URL和方法。例如,使用Axios库进行请求:
    import axios from 'axios';
    
    const elasticsearchUrl = 'http://localhost:9200';
    
    const searchDocuments = async (indexName, query) => {
        try {
            const response = await axios.get(`${elasticsearchUrl}/${indexName}/_search`, {
                params: {
                    q: query
                }
            });
            return response.data.hits.hits;
        } catch (error) {
            console.error('Error searching documents:', error);
            return [];
        }
    };
    
    // 示例调用
    searchDocuments('my-index', 'example').then(documents => {
        console.log('Documents:', documents);
    });
    

通过以上配置,前端应用可以顺利连接到Elasticsearch,实现数据的查询和操作。跨域配置是前后端分离架构中不可或缺的一部分,正确配置跨域可以确保应用的正常运行和数据的安全传输。

四、总结

本文详细介绍了如何在SpringBoot项目中集成Elasticsearch(ES),并进行了基本的操作。首先,我们通过添加依赖和配置文件,成功搭建了SpringBoot与Elasticsearch的环境。接着,我们学习了Linux基础命令,掌握了文件编辑和系统管理的基本技能。随后,我们详细讲解了如何使用Elasticsearch进行索引的创建、删除、更新和文档的增删改查等操作。特别值得一提的是,高亮显示功能在ES7.9.x版本中得到了增强,但在7.7版本中可能会出现报错,因此建议使用7.9.x或更高版本。

为了提高操作的便捷性和效率,我们推荐使用es-head和Kibana这两个图形化工具。es-head提供了直观的界面,使得索引管理和文档操作更加简单;而Kibana不仅支持索引管理和文档操作,还提供了丰富的可视化功能,使得数据分析和管理更加直观和高效。

最后,我们讨论了在前后端分离的架构中,如何进行跨域配置,确保前端应用能够顺利连接到Elasticsearch。通过修改Elasticsearch的配置文件并重启服务,可以实现跨域访问,确保数据的正常传输和应用的稳定运行。

希望本文的内容对您的项目有所帮助,使您能够在SpringBoot项目中更高效地使用Elasticsearch。