spring-data-elasticsearch-如何对嵌套字段使用条件

taor4pac  于 2021-06-10  发布在  ElasticSearch
关注(0)|答案(1)|浏览(486)

我正在使用spring数据elasticsearch(4.0.1)和elasticsearch一起查询文档。我想用条件对嵌套文档进行嵌套查询,我对实体类进行了注解,但不能用引用嵌套字段的条件进行查询。

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

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

zzwlnbp8

zzwlnbp81#

您可能希望从spring数据使用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);

相关问题