gpt4 book ai didi

java - CQEngine可以在另一个对象中查询一个对象吗

转载 作者:行者123 更新时间:2023-11-29 08:44:03 25 4
gpt4 key购买 nike

有谁知道 CQEngine 是否可以在其他对象中查询对象?我希望能够查询用户、订单和产品。

这可以用 CQEngine 完成还是我需要展平对象?

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

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

public class Products {
public String name;
}

最佳答案

是的,您只需要定义一个 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,其中每个用户都有多个订单,每个订单都有多个产品。这些产品是您可能会在电影院找到的零食。它在集合中搜索订购“士力架”的用户。

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 上找到该示例的完整源代码。 . (我刚刚将其添加为新示例!)

关于java - CQEngine可以在另一个对象中查询一个对象吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37766895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com