您的位置:首页 > 游戏 > 手游 > 谷粒商城实战笔记-126-全文检索-ElasticSearch-整合-测试保存

谷粒商城实战笔记-126-全文检索-ElasticSearch-整合-测试保存

2024/10/6 16:22:58 来源:https://blog.csdn.net/epitomizelu/article/details/140905429  浏览:    关键词:谷粒商城实战笔记-126-全文检索-ElasticSearch-整合-测试保存

文章目录

  • 一,谷粒商城实战笔记-126-全文检索-ElasticSearch-整合-测试保存
    • 1,在Elasticsearch的配置类中增加通用设置
    • 2,索引数据
    • 3,验证

一,谷粒商城实战笔记-126-全文检索-ElasticSearch-整合-测试保存

1,在Elasticsearch的配置类中增加通用设置

在这里插入图片描述

public static final RequestOptions COMMON_OPTIONS;static {RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();// builder.addHeader("Authorization", "Bearer " + TOKEN);// builder.setHttpAsyncResponseConsumerFactory(//         new HttpAsyncResponseConsumerFactory//                 .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));COMMON_OPTIONS = builder.build();}

这段代码的主要作用是:

  • 配置客户端请求时携带的认证信息(如认证令牌)。
  • 定义了客户端处理大文件响应的方式,通过设置一个较大的缓冲区大小。

这些配置选项将在后续使用Elasticsearch客户端执行请求时被应用,比如在后面代码片段中 restHighLevelClient.index(request, COMMON_OPTIONS),其中 COMMON_OPTIONS 被用作请求选项传递给客户端。这样,每次发送请求时都会自动包含这些设置,无需每次都手动配置。

2,索引数据

	public void indexData() throws IOException {IndexRequest request = new IndexRequest("users");request.id("1");   //数据的idUser user = new User();user.setName("zhangsan");user.setAge(18);user.setGender("男");String jsonString = JSON.toJSONString(user);request.source(jsonString, XContentType.JSON);IndexResponse index = restHighLevelClient.index(request, GulimallElasticSearchConfig.COMMON_OPTIONS);System.out.println(index);}class User {String name;int age;String gender;String json() {return JSON.toJSONString(this);}}

这段Java代码使用了Elasticsearch的REST High-Level Client来索引(存储)一条文档到Elasticsearch中。

  1. IndexRequest request = new IndexRequest("users");

    • 创建一个IndexRequest对象,该对象指定要将数据索引到名为"users"的索引中。
  2. request.id("1");

    • 设置索引请求中的文档ID为"1"。在Elasticsearch中,每个文档都有一个唯一标识符(ID),用于标识和检索文档。
  3. String jsonString = JSON.toJSONString(user);

    • 使用JSON库(例如Jackson或fastjson)将User对象转换为JSON格式的字符串。这里假设使用的是fastjson库。

4 request.source(jsonString, XContentType.JSON);

  • 将JSON字符串设置为IndexRequest的源数据,并指明内容类型为JSON。
  1. IndexResponse index = restHighLevelClient.index(request, GulimallElasticSearchConfig.COMMON_OPTIONS);
    • 使用REST High-Level Client执行索引操作。restHighLevelClient是Elasticsearch客户端实例,通过它发送索引请求。GulimallElasticSearchConfig.COMMON_OPTIONS是一个配置选项,通常用于设置请求的超时和其他参数。

这段代码执行完成后,会在Elasticsearch的users索引中创建一个ID为1的文档,包含用户的名字、年龄和性别信息。

3,验证

保存完成后,Kibana中可以查询到这条文档。

GET users/_search

在这里插入图片描述
也可以使用Java Api进行验证。

import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.ElasticsearchException;// 假设 restHighLevelClient 已经初始化好了
RestHighLevelClient client = restHighLevelClient;// 创建一个GetRequest
GetRequest getRequest = new GetRequest("users", "1");// 执行GET请求
try {GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);// 检查文档是否存在if (getResponse.isExists()) {// 获取文档的源数据String jsonString = getResponse.getSourceAsString();System.out.println("Document source: " + jsonString);// 如果你想解析JSON并获取特定字段,可以使用JSON库User user = JSON.parseObject(jsonString, User.class);System.out.println("Name: " + user.getName());System.out.println("Age: " + user.getAge());System.out.println("Gender: " + user.getGender());} else {System.out.println("Document not found.");}
} catch (ElasticsearchException e) {System.err.println("Error getting document: " + e.getMessage());
} catch (IOException e) {System.err.println("IO error getting document: " + e.getMessage());
}

要验证文档是否已成功保存到Elasticsearch中,你可以使用Elasticsearch客户端执行GET请求来检索该文档。以下是一个简单的示例,说明如何使用REST High-Level Client检索刚刚索引的文档。

首先,你需要确保你有客户端实例 restHighLevelClient 可用,并且已经定义了 COMMON_OPTIONS。然后,你可以使用以下代码来获取文档:

import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.ElasticsearchException;// 假设 restHighLevelClient 已经初始化好了
RestHighLevelClient client = restHighLevelClient;// 创建一个GetRequest
GetRequest getRequest = new GetRequest("users", "1");// 执行GET请求
try {GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);// 检查文档是否存在if (getResponse.isExists()) {// 获取文档的源数据String jsonString = getResponse.getSourceAsString();System.out.println("Document source: " + jsonString);// 如果你想解析JSON并获取特定字段,可以使用JSON库User user = JSON.parseObject(jsonString, User.class);System.out.println("Name: " + user.getName());System.out.println("Age: " + user.getAge());System.out.println("Gender: " + user.getGender());} else {System.out.println("Document not found.");}
} catch (ElasticsearchException e) {System.err.println("Error getting document: " + e.getMessage());
} catch (IOException e) {System.err.println("IO error getting document: " + e.getMessage());
}
  1. 创建GetRequest:

    • 使用 new GetRequest("users", "1") 创建一个 GetRequest 对象,其中 "users" 是索引名称,"1" 是文档的ID。
  2. 执行GET请求:

    • 使用 client.get(getRequest, RequestOptions.DEFAULT) 发送GET请求。在这里我们使用了默认的 RequestOptions,如果你之前定义了自定义的 RequestOptions,你可以将 RequestOptions.DEFAULT 替换为 COMMON_OPTIONS
  3. 处理响应:

    • getResponse.isExists() 检查文档是否存在。
    • getResponse.getSourceAsString() 获取文档的源数据作为字符串。
    • 使用JSON库(例如Jackson或fastjson)将字符串反序列化为 User 对象,以便于进一步处理。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com