2016-06-11 85 views
1

有谁知道CQEngine是否可以查询其他对象中的对象?我希望能够查询用户,订单和产品。CQEngine可以查询另一个对象内的对象

这可以用CQEngine完成,还是需要平整物体?

public class User { 
    public List<Orders> orders; 
} 

public class Orders { 
    public List<Products> products; 
} 

public class Products { 
    public String name; 
} 

回答

3

是的,你只需要定义一个CQEngine属性将从您要搜索嵌套对象返回的值。

例如,此属性将检索由特定用户放置的订单中包含的每个产品的名称。

static final Attribute<User, String> PRODUCT_NAMES_ORDERED = new MultiValueAttribute<User, String>() { 
    public Iterable<String> getValues(User user, QueryOptions queryOptions) { 
     return user.orders.stream() 
       .map(order -> order.products).flatMap(Collection::stream) 
       .map(product -> product.name)::iterator; 
    } 
}; 

你可以任意在此属性添加索引,以加快查询就可以了。

下面是一个示例,它设置了IndexedCollection个用户,其中每个用户都有多个订单,并且每个订单都有多个产品。这些产品是您可能在电影院看到的小吃。它搜索订购“Snickers酒吧”的用户。

package com.googlecode.cqengine.examples.nestedobjects; 

import com.googlecode.cqengine.*; 
import com.googlecode.cqengine.attribute.*; 
import com.googlecode.cqengine.query.option.QueryOptions; 
import java.util.*; 
import static com.googlecode.cqengine.query.QueryFactory.*; 
import static java.util.Arrays.asList; 
import static java.util.Collections.singletonList; 

public class NestedObjectsExample { 

    public static void main(String[] args) { 
     Order order1 = new Order(asList(new Product("Diet Coke"), new Product("Snickers Bar"))); 
     Order order2 = new Order(singletonList(new Product("Sprite"))); 
     User user1 = new User(1, asList(order1, order2)); 

     Order order3 = new Order(asList(new Product("Sprite"), new Product("Popcorn"))); 
     User user2 = new User(2, singletonList(order3)); 

     Order order4 = new Order(singletonList(new Product("Snickers Bar"))); 
     User user3 = new User(3, singletonList(order4)); 

     IndexedCollection<User> users = new ConcurrentIndexedCollection<>(); 
     users.addAll(asList(user1, user2, user3)); 

     users.retrieve(equal(PRODUCT_NAMES_ORDERED, "Snickers Bar")).forEach(user -> System.out.println(user.userId)); 
     // ...prints 1, 3 
    } 

} 

顺便说一句,我CQEngine的作者,你可以找到在CQEngine site这个例子的完整源代码。 (我刚刚添加了这个作为一个新的例子!)

+0

这实际上是惊人的。它将我的项目开发时间缩短了一半。谢谢 –

+0

没问题,乐于帮忙! – npgall

相关问题