


How to use Java to develop a full-text search application based on Elasticsearch
How to use Java to develop a full-text retrieval application based on Elasticsearch
Full-text retrieval is a very important technology in today's information age. It can quickly and accurately retrieve data from Search a large amount of text data for keywords or related information that users need. As an open source distributed search engine, Elasticsearch has been widely used for its efficient full-text retrieval capabilities, real-time data analysis and scalability. This article will introduce how to use Java to develop a full-text search application based on Elasticsearch, and provide specific code examples.
- Preparation work
Before starting development, we need to prepare the following work: - Install the Java development environment (JDK)
- Install the Elasticsearch server, and Start the service
- Import the Elasticsearch Java client library, for example, use Maven to import the following dependencies:
<dependencies> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>7.10.0</version> </dependency> </dependencies>
- Create the Elasticsearch client
First, we need to create a Client used to connect to the Elasticsearch server. You can create a client instance using the following code:
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; } }
- Create Index
Next, we need to create an index (Index) to store our document data. Indexes are similar to tables in a database, and we can store different types of document data in different indexes. You can use the following code to create an 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(); } } }
- Index document
After having the index, we can store the document data into the index. A document is similar to a record in a database. We can store multiple documents under the same index. You can use the following code to store document data in the index:
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(); } } }
- Search for documents
With the document index, we can search for documents containing keywords through full-text retrieval. . You can use the following code to perform document search:
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(); } } }
Using the above code example, we can complete the development of a full-text retrieval application based on Elasticsearch. By creating an index, indexing documents, and searching documents, we can achieve efficient and accurate full-text retrieval. Of course, in addition to the basic functions shown above, Elasticsearch also supports various advanced queries, aggregate analysis, distributed deployment and other features, and can be further developed and expanded according to specific needs. I hope this article is helpful to you, and I wish you greater success in the field of full-text retrieval!
The above is the detailed content of How to use Java to develop a full-text search application based on Elasticsearch. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
