Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 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" : "[email protected]"
        }
      }
    ]
  }
}

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 Answer

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
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...