如何使用Java和ElasticSearch实现全文搜索
大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!今天我们来探讨如何使用Java和ElasticSearch实现全文搜索。ElasticSearch是一个分布式搜索和分析引擎,能够处理大规模数据并提供实时搜索功能。在本文中,我们将介绍如何使用Java客户端与ElasticSearch进行交互,实现简单的全文搜索功能。
1. 准备工作
首先,我们需要确保ElasticSearch已经安装并运行在本地或服务器上。然后,创建一个新的Maven项目,并在pom.xml中添加所需的依赖。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.juwatech</groupId>
<artifactId>elasticsearch-demo</artifactId>
<version>1.0.0</version>
<dependencies>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. 创建ElasticSearch客户端
接下来,我们需要创建一个ElasticSearch客户端,用于连接到ElasticSearch服务器。
ElasticSearchClient.java
package cn.juwatech.elasticsearch.demo;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
public class ElasticSearchClient {
private static final String HOST = "localhost";
private static final int PORT = 9200;
private static RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost(HOST, PORT, "http")
)
);
public static RestHighLevelClient getClient() {
return client;
}
public static void closeClient() throws IOException {
client.close();
}
}
3. 索引数据
我们需要定义一个Java类来表示我们要索引的数据,并创建一个方法将数据索引到ElasticSearch中。
Article.java
package cn.juwatech.elasticsearch.demo;
public class Article {
private String id;
private String title;
private String content;
// Getters and Setters
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
ArticleService.java
package cn.juwatech.elasticsearch.demo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.util.UUID;
public class ArticleService {
private static final ObjectMapper MAPPER = new ObjectMapper();
public void indexArticle(Article article) throws IOException {
article.setId(UUID.randomUUID().toString());
IndexRequest indexRequest = new IndexRequest("articles")
.id(article.getId())
.source(MAPPER.writeValueAsString(article), XContentType.JSON);
IndexResponse indexResponse = ElasticSearchClient.getClient().index(indexRequest, RequestOptions.DEFAULT);
System.out.println("Indexed article with id: " + indexResponse.getId());
}
}
4. 搜索数据
为了实现全文搜索功能,我们需要编写一个方法来从ElasticSearch中搜索数据。
ArticleService.java
package cn.juwatech.elasticsearch.demo;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.SearchHit;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ArticleService {
// 其他方法省略
public List<Article> searchArticles(String keyword) throws IOException {
SearchRequest searchRequest = new SearchRequest("articles");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(QueryBuilders.multiMatchQuery(keyword, "title", "content"));
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = ElasticSearchClient.getClient().search(searchRequest, RequestOptions.DEFAULT);
List<Article> articles = new ArrayList<>();
for (SearchHit hit : searchResponse.getHits().getHits()) {
articles.add(new ObjectMapper().readValue(hit.getSourceAsString(), Article.class));
}
return articles;
}
}
5. 测试全文搜索功能
我们创建一个主类来测试索引和搜索功能。
Main.java
package cn.juwatech.elasticsearch.demo;
import java.io.IOException;
import java.util.List;
public class Main {
public static void main(String[] args) {
ArticleService articleService = new ArticleService();
// 索引示例文章
Article article = new Article();
article.setTitle("ElasticSearch入门");
article.setContent("ElasticSearch是一个分布式搜索和分析引擎...");
try {
articleService.indexArticle(article);
} catch (IOException e) {
e.printStackTrace();
}
// 搜索文章
try {
List<Article> articles = articleService.searchArticles("ElasticSearch");
articles.forEach(a -> System.out.println("Found article: " + a.getTitle()));
} catch (IOException e) {
e.printStackTrace();
}
// 关闭客户端
try {
ElasticSearchClient.closeClient();
} catch (IOException e) {
e.printStackTrace();
}
}
}
6. 总结
本文介绍了如何使用Java和ElasticSearch实现全文搜索。我们首先创建了一个ElasticSearch客户端,然后定义了一个简单的Article类,并实现了索引和搜索功能。通过这些示例代码,我们可以快速上手并在实际项目中应用ElasticSearch进行全文搜索。
本文著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!