Spring数据elasticsearch查询嵌套对象数组

时间:2016-09-05 00:45:22

标签: spring elasticsearch spring-data-elasticsearch

我有以下模型,文章,可以分配标签(如主题标签):

for

这是标签模型:

@Entity
@Table(name="article")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
        name="post_type",
        discriminatorType=DiscriminatorType.STRING
)
@DiscriminatorValue("text")
@Document(indexName="article", type="article")
public class Article implements Serializable {
    @org.springframework.data.annotation.Id
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name="articleId")
    private int articleId;
    ... data for article...
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "user_id", nullable = false)
    private User userId;

    @Field( type = FieldType.Nested)
    @ManyToMany(fetch = FetchType.EAGER)
    private Set<Tag> tags = new LinkedHashSet<>();Simple {tagName, tagId}

使用spring-data-elasticsearch我正在尝试使用tagName进行查询。我尝试了以下QueryBuilder查询:

@Entity
@Table(name = "tag")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
        name="tag_type",
        discriminatorType=DiscriminatorType.STRING
)
@DiscriminatorValue("tag")
public class Tag {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name="id")
    private int tagId;

    @Column(name="tag_name")
    private String tagName;

但最终得到以下堆栈错误:

QueryBuilder builder = nestedQuery("tags.tagName", matchQuery("tags.tagName", tagName));
QueryBuilder builder = nestedQuery("tags", matchQuery("tags.tagName", tagName));

我做错了什么?

1 个答案:

答案 0 :(得分:2)

尝试使用以下 SearchQuery 设置:

QueryBuilder builder = matchAllQuery();
FilterBuilder filterBuilder = boolFilter().must(termFilter("tags.tagName", tagName));

SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.filteredQuery(builder, filterBuilder))

您应该使用过滤后的查询并匹配所有实体。