使用GET API通过elasticsearch和JAVA API检索单个术语,可以按照以下步骤进行:
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.elasticsearch.search.lookup.SourceLookup;
import java.io.IOException;
public class ElasticsearchGetAPIExample {
public static void main(String[] args) {
// 创建RestHighLevelClient实例
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 构建GetRequest对象
GetRequest getRequest = new GetRequest("your_index", "your_type", "your_id");
// 可选:设置检索的源字段
String[] includes = Strings.EMPTY_ARRAY;
String[] excludes = new String[]{"field_to_exclude"};
FetchSourceContext fetchSourceContext =
new FetchSourceContext(true, includes, excludes);
getRequest.fetchSourceContext(fetchSourceContext);
// 可选:设置检索超时时间
getRequest.timeout(TimeValue.timeValueSeconds(1));
try {
// 执行检索请求
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
// 处理检索结果
if (getResponse.isExists()) {
String sourceAsString = getResponse.getSourceAsString();
System.out.println("检索结果:" + sourceAsString);
} else {
System.out.println("未找到指定文档");
}
} catch (IOException e) {
e.printStackTrace();
}
// 关闭RestHighLevelClient连接
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
领取专属 10元无门槛券
手把手带您无忧上云