Spring Data ElasticSearch parnt/child search

http://stackoverflow.com/questions/23730641/parent-child-relationships-in-spring-data-elastic-search


父实体类及子实体类的搜索方法如下:

 @Document(indexName = "parent-child", type = "parent-entity")
    public class ParentEntity {


     @Id
     private String id;
     @Field(type = FieldType.String, index = FieldIndex.analyzed, store = true)
     private String name;
         // setter/getter

    public ParentEntity() {
    }

    public ParentEntity(String id, String name) {
      this.id = id;
      this.name = name;
    }
    }


   @Document(indexName = "parent-child", type = "child-entity")
   public class ChildEntity {

     @Id
     private String id;
     @Field(type = FieldType.String, store = true)
     @Parent(type = "parent-entity")
     private String parentId;
     @Field(type = FieldType.String, index = FieldIndex.analyzed, store = true)
     private String name;

     public ChildEntity() {
     }

     public ChildEntity(String id, String parentId, String name) {
      this.id = id;
      this.parentId = parentId;
      this.name = name;
     }
      }

// 为父实体类做索引(你还可以使用许多其它的方法做索引 例如: repositories)

ParentEntity parent1 = new ParentEntity("parent1", "First Parent");
    IndexQuery parentIndex1 = new IndexQuery();
    parentIndex1.setId(parent1.getId());
    parentIndex1.setObject(parent1);
    elasticsearchTemplate.index(parentIndex1);

    ParentEntity parent2 = new ParentEntity("parent2", "Second Parent");
    IndexQuery parentIndex2 = new IndexQuery();
    parentIndex2.setId(parent2.getId());
    parentIndex2.setObject(parent2);
    elasticsearchTemplate.index(parentIndex2);

// 为子实体类做索引

ChildEntity child1 = new ChildEntity("child1", parent1.getId(), "First");
    IndexQuery childIndex1 = new IndexQuery();
    childIndex1.setId(child1.getId());
    childIndex1.setObject(child1);
    childIndex1.setParentId(child1.getParentId());
    elasticsearchTemplate.index(childIndex1);

    ChildEntity child2 = new ChildEntity("child2", parent1.getId(), "Second");
    IndexQuery childIndex2 = new IndexQuery();
    childIndex2.setId(child2.getId());
    childIndex2.setObject(child2);
    childIndex2.setParentId(child2.getParentId());
    elasticsearchTemplate.index(childIndex2);

//搜索

对于主从结构的实体类,有三种可选的搜索方法:

1.has children 点击打开链接

2.has parent  点击打开链接

3.top children  点击打开链接

QueryBuilder query = topChildrenQuery("child-entity", QueryBuilders.termQuery("name", child1name.toLowerCase()));
    SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(query).build();

    List<ParentEntity> parents = elasticsearchTemplate.queryForList(searchQuery, ParentEntity.class);











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值