javaelasticsearchelasticsearch-jest

Find document by Id with additional filter in Elasticsearch using Java Jest


I am trying to use JEST Java API to get Document by Id and have an additional check if an element is present

For example lets say I have a java object User having fields id, firstname, lastname and if the index for document does not have firstname element at all I want to filter it out

Right now I am doing it something like this

public Optional<User> findById(long id) {
    try {
      Get action = new Get.Builder(INDEX_ALIAS, String.valueOf(id)).build();
      User user= execute(action).getSourceAsObject(User.class);
      if (user!= null && user.getFirstName()!=null)) {
        return Optional.ofNullable(user);
      } else {
        return Optional.empty();
      }
    } catch (NoSuchElementException ex) {
      return Optional.empty();
    }
  }

Is there a better way to have this check in query itself.


Solution

  • As Abhijit mentioned, exits query is probably what you are looking for.

    Returns documents that contain an indexed value for a field.

    In the High-Level Java Client it can be used with the ExistsQueryBuilder.