使用Elasticsearch与Java进行全文搜索

全文搜索是现代应用中不可或缺的功能之一,它允许用户通过关键词快速找到所需的信息。Elasticsearch是一个基于Lucene库的分布式搜索和分析引擎,它提供了强大的全文搜索功能。本文将详细介绍如何使用Java与Elasticsearch进行全文搜索,并提供详细的代码示例。

1. 环境准备

在开始之前,确保你已经安装了以下软件:

  • Java 8或更高版本
  • Elasticsearch 7.x或更高版本
  • IntelliJ IDEA或其他Java IDE

1.1 安装Elasticsearch

你可以从Elasticsearch官方网站下载并安装Elasticsearch。安装完成后,启动Elasticsearch服务:

复制代码
./bin/elasticsearch

默认情况下,Elasticsearch将在http://localhost:9200上运行。

1.2 添加Elasticsearch依赖

在你的Java项目中,添加Elasticsearch的Java客户端依赖。如果你使用Maven,可以在pom.xml中添加以下依赖:

XML 复制代码
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.10.0</version>
</dependency>

2. 连接到Elasticsearch

首先,我们需要创建一个Elasticsearch客户端并连接到Elasticsearch服务。以下是一个简单的示例:

java 复制代码
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

public class ElasticsearchClient {
    private static RestHighLevelClient client;

    public static RestHighLevelClient getClient() {
        if (client == null) {
            client = new RestHighLevelClient(
                    RestClient.builder(
                            new HttpHost("localhost", 9200, "http")
                    )
            );
        }
        return client;
    }

    public static void closeClient() {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3. 创建索引

在Elasticsearch中,数据存储在索引中。我们需要创建一个索引来存储我们的文档。以下是一个创建索引的示例:

java 复制代码
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;

public class IndexCreator {
    public static void createIndex(String indexName) {
        RestHighLevelClient client = ElasticsearchClient.getClient();
        CreateIndexRequest request = new CreateIndexRequest(indexName);

        try {
            CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
            if (response.isAcknowledged()) {
                System.out.println("Index created: " + indexName);
            } else {
                System.err.println("Failed to create index: " + indexName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4. 索引文档

接下来,我们将文档索引到Elasticsearch中。以下是一个索引文档的示例:

java 复制代码
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

public class DocumentIndexer {
    public static void indexDocument(String indexName, String id, String jsonDocument) {
        RestHighLevelClient client = ElasticsearchClient.getClient();
        IndexRequest request = new IndexRequest(indexName)
                .id(id)
                .source(jsonDocument, XContentType.JSON);

        try {
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
            System.out.println("Document indexed with ID: " + response.getId());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

5. 搜索文档

现在,我们将进行全文搜索。以下是一个简单的搜索示例:

java 复制代码
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;

public class DocumentSearcher {
    public static void searchDocuments(String indexName, String query) {
        RestHighLevelClient client = ElasticsearchClient.getClient();
        SearchRequest searchRequest = new SearchRequest(indexName);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchQuery("content", query));
        searchRequest.source(searchSourceBuilder);

        try {
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            searchResponse.getHits().forEach(hit -> {
                System.out.println("Document ID: " + hit.getId());
                System.out.println("Document Source: " + hit.getSourceAsString());
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6. 完整示例

以下是一个完整的示例,展示了如何创建索引、索引文档和进行搜索:

java 复制代码
public class ElasticsearchExample {
    public static void main(String[] args) {
        String indexName = "my_index";
        String documentId = "1";
        String jsonDocument = "{" +
                "\"title\": \"Elasticsearch入门\"," +
                "\"content\": \"Elasticsearch是一个强大的全文搜索和分析引擎。\"" +
                "}";

        // 创建索引
        IndexCreator.createIndex(indexName);

        // 索引文档
        DocumentIndexer.indexDocument(indexName, documentId, jsonDocument);

        // 搜索文档
        DocumentSearcher.searchDocuments(indexName, "Elasticsearch");

        // 关闭客户端
        ElasticsearchClient.closeClient();
    }
}

7. 总结

本文详细介绍了如何使用Java与Elasticsearch进行全文搜索。我们从环境准备开始,逐步讲解了如何连接到Elasticsearch、创建索引、索引文档和进行搜索。通过这些步骤和代码示例,你应该能够开始在自己的项目中使用Elasticsearch进行全文搜索。希望这篇文章对你有所帮助!

相关推荐
wwj20246 分钟前
跨地域经营企业HR平台选型:人才布局、权限治理与合规适配
java·运维·人工智能
YuePeng+42 分钟前
一个注解,生成一个完整管理后台:erupt 上手实录
java·spring boot·低代码·开源
Rain的Java大神之路1 小时前
读懂 Spring 源码,从"能编译"开始:Spring 7.0.8 环境搭建 + 阅读方法全攻略
java·后端·spring
9624561 小时前
考勤汇总看起来异常,导出又报 403:一次原版对照与重建兼容性修复复盘
java
Lethehong1 小时前
从轻点到落块:Rokid AIUI 游戏《叠叠乐》开发实践
java·开发语言·游戏
岳涛_daemon2 小时前
什么都没配,ES 的 HNSW 早停在 9.3 前后创建的索引默认值不一样,按创建版本算
elasticsearch
darkb1rd2 小时前
WPS 每日任务自动化:签到、抽奖和试用一次配好
java·自动化·wps
夜雪轻寒3 小时前
AI 工具踩坑录:Prompt 我越写越长,模型反而越来越笨,删到第三版才明白它在装
java·开发语言·人工智能·语言模型·自然语言处理·prompt
Helix2503 小时前
JDK IO流与文件操作NIO.2实战:Files/Path/InputStream/OutputStream读写完整教程
java·jdk·文件读写·inputstream·java io·files·nio.2
nice_lcj5203 小时前
在 Spring Boot 里学会使用 RabbitMQ:从入门到实战
java·spring boot·spring·rabbitmq·java-rabbitmq