Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

java - Elasticsearch: Fetch document _id by source id

I've recently started using ElasticSearch and I am not able to get document _id(E2EZ4nYBaAtUNwzCDsL9) using source id(26.0).

Example:

Query:

GET /_search?index=xyz
{
  "_source": ["firstName", "lastName", "id", "email"]
}

Below is my elastic search query result:

{
  "took" : 431,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 98,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "xyz",
        "_type" : "_doc",
        "_id" : "E2EZ4nYBaAtUNwzCDsL9",
        "_score" : 1.0,
        "_source" : {
          "lastName" : "mehta",
          "firstName" : "zenny",
          "id" : 26.0,
          "email" : "zmehta@gmail.com"
        }
      }
    ]
  }
}

Below I have attached code to fetch _id from the source id field.

SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

    QueryBuilder matchSpecificFieldQuery = QueryBuilders.multiMatchQuery(id, "id");
    sourceBuilder.query(matchSpecificFieldQuery);
    sourceBuilder.from(0);
    sourceBuilder.size(5);
    sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); // how long the search is allowed to take

    SearchRequest searchRequest = new SearchRequest();

    String[] includes = new String[] { "id" };

    String[] excludes = Strings.EMPTY_ARRAY;
    sourceBuilder.fetchSource(includes, excludes);
    searchRequest.indices(INDEX_TYPE);
    searchRequest.source(sourceBuilder);

    SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

    String docId = searchResponse.getHits().getHits()[0].getId();

    DeleteRequest deleteRequest = new DeleteRequest(INDEX_TYPE, docId);

But nothing seems to work.

Currently, I have only the id field value, But for the delete request, I need to fetch _id using source id. How do I delete a record by _id in ElasticSearch?

question from:https://stackoverflow.com/questions/65843360/elasticsearch-fetch-document-id-by-source-id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should call client by deleteRequest like this.

DeleteRequest deleteRequest = new DeleteRequest(INDEX_TYPE, docId);

DeleteResponse deleteResponse = client.delete(deleteRequest,questOptions.DEFAULT);

if (deleteResponse.getResult() == DocWriteResponse.Result.NOT_FOUND) {
   // Do something if the document to be deleted was not found
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...