微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Spring Data Elasticsearch-如何对嵌套字段使用条件

如何解决Spring Data Elasticsearch-如何对嵌套字段使用条件

我正在同时使用spring-data-elasticsearch(4.0.1)和elasticsearch来查询文档。我想使用Criteria对嵌套文档进行嵌套查询,我为实体类添加了注释,但无法使用引用嵌套字段的条件进行查询

{
  "user" : {
    "mappings" : {
      "properties" : {
        "contacts" : {
          "type" : "nested","properties" : {
            "description" : {
              "type" : "text"
            },"id" : {
              "type" : "long"
            }
          }
        },"id" : {
          "type" : "long"
        },"name" : {
          "type" : "text"
        }
      }
    }
  }
}
{
  "took" : 5,"timed_out" : false,"_shards" : {
    "total" : 1,"successful" : 1,"skipped" : 0,"Failed" : 0
  },"hits" : {
    "total" : {
      "value" : 1,"relation" : "eq"
    },"max_score" : 1.0,"hits" : [
      {
        "_index" : "user","_type" : "_doc","_id" : "MgHFrXUBYAZ","_score" : 1.0,"_source" : {
          "id" : 1,"name" : "Peter","contacts" : [
            {
              "id" : 1,"description" : "foo"
            },{
              "id" : 2,"description" : "bar"
            }
          ]
        }
      }
    ]
  }
}
@Document(indexName = "user",createIndex = false)
public class User {

  @Id
  private Long id;

  @Field(type = FieldType.nested)
  private List<Contacts> contactos;
}
public class Contacts {

  @Field(type = FieldType.Long)
  private Long id;

  @Field(type = FieldType.Text)
  private String description;
}
Criteria criteria = new Criteria("contacts.id").is(1);
CriteriaQuery query = new CriteriaQuery(criteria).setPageable(pageable);
SearchHits<User> searchHits = this.elasticsearchRestTemplate.search(query,User.class);

我没有得到任何结果,我在做什么错了?

解决方法

您可能想使用Spring Data中的NativeSearchQueryBuilder来实现此嵌套查询。以下是有关其外观的摘要:

QueryBuilder builder = nestedQuery("contactos",boolQuery().must(termQuery("contacts.id",1)));

SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
List<User> users = elasticsearchTemplate.queryForList(searchQuery,User.class);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。