侧边栏壁纸
博主头像
一个九零后的萤火虫博主等级

行动起来,活在当下

  • 累计撰写 33 篇文章
  • 累计创建 7 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

elasticsearch(二)java 使用同步步方法进行查询操作

Administrator
2024-01-25 / 0 评论 / 0 点赞 / 10 阅读 / 5476 字

一、 基本步骤:

1.创建连接对象:

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9200, "http")
                )
        );

2.创建请求对象:

 GetRequest getRequest = new GetRequest("posts", "doc", "16");

3.为请求对象设置参数:

(1)设置查询的版本:
getRequest.version(2) 可以不设置,如果设置所要查询的文档版本号为2,如果当前版本号为4,则查询失败,报错如下


{
    "error":{
        "root_cause":[
            {
                "type":"version_conflict_engine_exception",
                "reason":"[doc][16]: version conflict, current version [4] is different than the one provided [2]",
                "index_uuid":"60e-U9cXSYqFGC34_gTrug",
                "shard":"3",
                "index":"posts"
            }
        ],
        "type":"version_conflict_engine_exception",
        "reason":"[doc][16]: version conflict, current version [4] is different than the one provided [2]",
        "index_uuid":"60e-U9cXSYqFGC34_gTrug",
        "shard":"3",
        "index":"posts"
    },
    "status":409
}

(2)设置查询的参数

a. 查询文档中指定的字段(如message和以Date结尾的字段): String[] includes = new String[]{"message", "*Date"}

查询文档中所有的字段:String[] includes = Strings.EMPTY_ARRAY;

b. 过滤掉文档中指定的字段(如message): String[] excludes = new String[]{"message"};

不过滤文档中任何字段:String[] excludes = Strings.EMPTY_ARRAY;

c. FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes);

其中includes可以传null,此时表示查询所有的字段

excludes也可以为null,此时表示不过滤掉任何字段

注: 如果includes和excludes包含同一个字段,则excludes起作用,也就是查询的字段会被过滤掉

d. 将设置的查询参数赋值给请求对象:

getRequest.fetchSourceContext(fetchSourceContext);

e.如果不希望返回结果中包含内容,可以进行如下设置:

getRequest.fetchSourceContext(FetchSourceContext.DO_NOT_FETCH_SOURCE);

默认是返回全部内容的

二、进行同步查询:

1,执行方法:
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);

2,根据返回的结果:

a.判断文档是否存在:

getResponse.isExists(),如果为true,则存在

b.将查询的文档内容转成字符串:

String sourceAsString = getResponse.getSourceAsString();

c.将查询的文档内容转换成Map对象:

Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();

3,同步方法查询的完整代码示例:


package com.example.elasticsearch.main;
 
 
import org.apache.http.HttpHost;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.Strings;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
 
import java.io.IOException;
import java.util.Map;
 
/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Weichang Zhong
 * @Date: 2018/11/7
 * @Time: 9:15
 * @Description:
 */
public class GetRequestMain {
 
    public static void main(String[] args) throws Exception{
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9200, "http")
                )
        );
 
 
        GetRequest getRequest = new GetRequest("posts", "doc", "16");
        getRequest.version(4);
        String[] includes = new String[]{"message", "*Date"};
        String[] excludes = Strings.EMPTY_ARRAY;
        FetchSourceContext fetchSourceContext =
                new FetchSourceContext(true, includes, excludes);
        getRequest.fetchSourceContext(fetchSourceContext);
 
        try {
            GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
            String index = getResponse.getIndex();
            String type = getResponse.getType();
            String id = getResponse.getId();
            System.out.println("index:" + index + "; type:" + type + "; id:" + id);
            if (getResponse.isExists()) {
                long version = getResponse.getVersion();
                String sourceAsString = getResponse.getSourceAsString();
                System.out.println("version:" + version + ",内容字符串:" + sourceAsString);
                Map<String, Object> sourceAsMap = getResponse.getSourceAsMap();
                byte[] sourceAsBytes = getResponse.getSourceAsBytes();
            } else {
                System.out.println("所查询的文档不存在!");
            }
        } catch (ElasticsearchException e) {
            if (e.status() == RestStatus.NOT_FOUND) {
                System.out.println("所查询的文档库不存在!");
            }else if(e.status() == RestStatus.CONFLICT) {
                System.out.println("与当前版本冲突");
            }
        }
    }
}

注意:无论文档类型或id不存在,只要文档库存在,getResponse都会得到返回的结果

而要是文档库不存在:GetRequest request = new GetRequest("does_not_exist", "doc", "1"); 或版本冲突,则查询结果会报异常,并以ElasticsearchException接收异常

0

评论区