使用Elasticsearch与Java进行全文搜索
创始人
2025-01-09 00:05:32
0

全文搜索是现代应用中不可或缺的功能之一,它允许用户通过关键词快速找到所需的信息。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中添加以下依赖:

     org.elasticsearch.client     elasticsearch-rest-high-level-client     7.10.0  

2. 连接到Elasticsearch

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

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中,数据存储在索引中。我们需要创建一个索引来存储我们的文档。以下是一个创建索引的示例:

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中。以下是一个索引文档的示例:

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. 搜索文档

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

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. 完整示例

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

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进行全文搜索。希望这篇文章对你有所帮助!

相关内容

热门资讯

必看攻略!wepoker怎么开... 必看攻略!wepoker怎么开辅助,wepoker有辅助功能吗,技巧教程(确实有挂)能透视中分为三种...
近日!红龙poker辅助工具,... 近日!红龙poker辅助工具,wpk透视辅助,竟然确实有挂(真的有挂)1、近日!红龙poker辅助工...
推荐一下!边锋干瞪眼辅助器,小... 推荐一下!边锋干瞪眼辅助器,小唐家乐园辅助,其实真的是有挂(哔哩哔哩)1、在边锋干瞪眼辅助器插件功能...
揭秘关于!wpk真的有透视嘛,... 揭秘关于!wpk真的有透视嘛,hhpoker有没有辅助,攻略教程(今日头条)1、完成辅助器v3.3的...
现有说明如下!约局吧德州可以透... 现有说明如下!约局吧德州可以透视吗,如何下载wpk透视版,果然存在有挂(有挂技术)暗藏猫腻,小编详细...
解迷一下!科乐天天踢有没有作比... 解迷一下!科乐天天踢有没有作比,家乡大二辅助免费,切实真的是有挂(哔哩哔哩)1、首先打开科乐天天踢有...
实测教程!hhpoker视频巡... 实测教程!hhpoker视频巡查真的假的,hhpoker德州有挂吗,技巧教程(有挂工具)1、免费辅助...
此事引发网友热议!wepoke... 此事引发网友热议!wepoker透视苹果系统,哈糖大菠萝助手,原来真的有挂(有挂神器)1、下载好we...
必备一下!jj斗地主麻将外卦挂... 必备一下!jj斗地主麻将外卦挂,九游破解辅助插件,其实是真的有挂(哔哩哔哩)1、游戏颠覆性的策略玩法...
必看攻略!hh poker插件... 必看攻略!hh poker插件下载,hhpoker辅助挂,插件教程(有挂总结)1、用户打开应用后不用...