ホームページ  >  記事  >  Java  >  Java を使用して Elasticsearch に基づく全文検索アプリケーションを開発する方法

Java を使用して Elasticsearch に基づく全文検索アプリケーションを開発する方法

WBOY
WBOYオリジナル
2023-09-21 13:33:11876ブラウズ

Java を使用して Elasticsearch に基づく全文検索アプリケーションを開発する方法

Java を使用して Elasticsearch に基づく全文検索アプリケーションを開発する方法

全文検索は、今日の情報化時代において非常に重要なテクノロジです。大量のテキストデータから、ユーザーが必要とするキーワードや関連情報を検索します。 Elasticsearch は、オープンソースの分散検索エンジンとして、その効率的な全文検索機能、リアルタイムのデータ分析、およびスケーラビリティにより広く使用されています。この記事では、Java を使用して Elasticsearch に基づく全文検索アプリケーションを開発する方法と、具体的なコード例を紹介します。

  1. 準備作業
    開発を開始する前に、次の作業を準備する必要があります。
  2. Java 開発環境 (JDK) のインストール
  3. Elasticsearch サーバーのインストールおよびサービスを開始します。
  4. Elasticsearch Java クライアント ライブラリをインポートします。たとえば、Maven を使用して次の依存関係をインポートします。
<dependencies>
  <dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.10.0</version>
  </dependency>
</dependencies>
  1. Elasticsearch クライアントを作成します
    最初に、Elasticsearch サーバーへの接続に使用するクライアントを作成する必要があります。次のコードを使用してクライアント インスタンスを作成できます。
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

public class ElasticsearchClient {
    public static RestHighLevelClient createClient() {
        // 配置Elasticsearch服务器地址
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        // 创建高级客户端实例
        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;
    }
}
  1. インデックスの作成
    次に、ドキュメント データを保存するためのインデックス (Index) を作成する必要があります。インデックスはデータベースのテーブルに似ており、さまざまな種類のドキュメント データをさまざまなインデックスに保存できます。次のコードを使用してインデックスを作成できます。
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;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentFactory.*;

public class IndexCreator {
    public static void createIndex(String indexName) {
        try {
            RestHighLevelClient client = ElasticsearchClient.createClient();
            
            // 创建索引请求
            CreateIndexRequest request = new CreateIndexRequest(indexName);
            
            // 设置索引的映射规则
            XContentBuilder mappingBuilder = XContentFactory.jsonBuilder();
            mappingBuilder.startObject();
            mappingBuilder.startObject("properties");
            mappingBuilder.startObject("title");
            mappingBuilder.field("type", "text");
            mappingBuilder.endObject();
            mappingBuilder.startObject("content");
            mappingBuilder.field("type", "text");
            mappingBuilder.endObject();
            mappingBuilder.endObject();
            mappingBuilder.endObject();
            
            request.mapping(mappingBuilder);
            
            // 执行创建索引请求
            CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
            
            // 处理响应结果
            if (response.isAcknowledged()) {
                System.out.println("索引创建成功:" + indexName);
            } else {
                System.out.println("索引创建失败:" + indexName);
            }
            
            // 关闭客户端连接
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  1. インデックス ドキュメント
    インデックスを取得した後、ドキュメント データをインデックスに保存できます。ドキュメントはデータベースのレコードに似ており、複数のドキュメントを同じインデックスの下に保存できます。次のコードを使用して、ドキュメント データをインデックスに保存できます。
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 documentId, String title, String content) {
        try {
            RestHighLevelClient client = ElasticsearchClient.createClient();
            
            // 创建文档索引请求
            IndexRequest request = new IndexRequest(indexName);
            request.id(documentId);
            request.source("title", title);
            request.source("content", content);
            
            // 执行文档索引请求
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
            
            // 处理响应结果
            if (response.status().getStatus() == 201) {
                System.out.println("文档索引成功:" + documentId);
            } else {
                System.out.println("文档索引失败:" + documentId);
            }
            
            // 关闭客户端连接
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  1. ドキュメントの検索
    ドキュメント インデックスを使用すると、全文検索を通じてキーワードを含むドキュメントを検索できます。 . .次のコードを使用してドキュメント検索を実行できます。
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.index.query.QueryBuilders.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;

public class DocumentSearcher {
    public static void searchDocument(String indexName, String keyword) {
        try {
            RestHighLevelClient client = ElasticsearchClient.createClient();
            
            // 创建搜索请求
            SearchRequest request = new SearchRequest(indexName);
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            sourceBuilder.query(QueryBuilders.matchQuery("content", keyword));
            request.source(sourceBuilder);
            
            // 执行搜索请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            
            // 处理响应结果
            if (response.getHits().getTotalHits().value > 0) {
                System.out.println("搜索结果:");
                for (SearchHit hit : response.getHits().getHits()) {
                    System.out.println(hit.getSourceAsString());
                }
            } else {
                System.out.println("未找到相关文档");
            }
            
            // 关闭客户端连接
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

上記のコード例を使用すると、Elasticsearch に基づく全文検索アプリケーションの開発を完了できます。インデックスを作成し、ドキュメントにインデックスを付け、ドキュメントを検索することで、効率的かつ正確な全文検索を実現できます。もちろん、Elasticsearch は上記の基本機能に加えて、さまざまな高度なクエリ、集計分析、分散デプロイメントなどの機能もサポートしており、特定のニーズに応じてさらに開発および拡張することができます。この記事があなたのお役に立てば幸いです。また、全文検索の分野でのさらなる成功をお祈りしています。

以上がJava を使用して Elasticsearch に基づく全文検索アプリケーションを開発する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。