使用Java Jest在Elasticsearch中通过ID查找文档并添加额外过滤条件。

huangapple go评论77阅读模式
英文:

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

问题

我正在尝试使用JEST Java API按ID获取文档,并额外检查是否存在某个元素。

例如,假设我有一个Java对象User,它具有id、firstname和lastname字段,如果文档的索引根本没有firstname元素,我想要将其过滤掉。

现在我正在像这样做:

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();
    }
  }

在查询本身中是否有更好的方式来进行此检查吗?

英文:

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&lt;User&gt; 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 &amp;&amp; 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.

答案1

得分: 1

正如Abhijit所提到的,存在查询可能是您正在寻找的内容。

返回包含字段的索引值的文档。

在High-Level Java客户端中,可以与ExistsQueryBuilder一起使用。

英文:

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.

huangapple
  • 本文由 发表于 2020年7月30日 22:41:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63175591.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定