简体   繁体   English

Spring Data Elasticsearch - 如何将标准与嵌套字段一起使用

[英]Spring Data Elasticsearch - How use Criteria with nested fields

I am using spring-data-elasticsearch (4.0.1) and elasticsearch together to query documents.我正在使用 spring-data-elasticsearch (4.0.1) 和 elasticsearch 来查询文档。 I'd like to do nested queries on nested documents with Criteria, I annotated the entities classes but cannot do the query with the criteria refering to nested field.我想使用 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);

I´m not getting any results, what am i doing wrong?我没有得到任何结果,我做错了什么?

You may want to implement this nested query using the NativeSearchQueryBuilder from Spring Data.您可能希望使用 Spring Data 中的NativeSearchQueryBuilder实现此嵌套查询。 Here is a snippet about how it would look like:这是一个关于它的外观的片段:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM