0

我正在尝试做一个看似简单的搜索查询,但无法确定是否有办法,如果有,是否有效。

我目前正在使用带有休眠搜索 4.3.0 的休眠。我想做的是搜索特定的集合。例如,我有一个包含 InventoryItem 列表的 Inventory 类。我想执行关键字搜索,其中仅搜索特定库存中的项目。是否可以将搜索限制在特定范围内。Inventory 和 InventoryItem 类都扩展了 DatastoreObject,它有一个 @Id Long id 字段作为它的主键。

库存类

/**
 * Inventory is a container of inventory objects.
 * 
 * @author chinshaw
 */
@Entity
@Indexed
public class Inventory extends DatastoreObject {

    @Size(min = 5, max = 256, message = "inventory name must be between 5 and 256 characters")
    @Column(length = 256)
    @Field
    private String name;

    @Size(max = 512, message = "inventory description cannot exceed 512 characters")
    @Column(length = 512)
    @Field
    private String description;

    /**
     * List of all inventory items in this object.
     */
    @IndexedEmbedded
    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)
    private List<InventoryItem> inventoryItems = new ArrayList<InventoryItem>();
...

我的 InventoryItem 类

/**
 * 
 * @author chinshaw
 */
@Entity
@Indexed
public class InventoryItem extends DatastoreObject implements IHasImage {

    /**
     * String manufacturer's serial number.
     */
    private String sin;

    /**
     * This is the name of the item.
     */
    @NotNull
    @Field
    private String name;

    /**
     * This is the text description of the object.
     */
    @Size(max = 200, message = "description must be less than 200 characters")
    @Field
    private String description;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "inventory_id")
    private Inventory inventory;

...

我目前正在尝试的示例代码

public List<InventoryItem> searchItems(Long inventoryId, String searchContext) {

    FullTextEntityManager session = Search.getFullTextEntityManager(getEntityManager());
    EntityTransaction tx = session.getTransaction();



    QueryBuilder qb = session.getSearchFactory().buildQueryBuilder().forEntity(InventoryItem.class).get();

    // How do I limit the search to only contain the inventoryId.
    org.apache.lucene.search.Query searchQuery = qb.keyword().onFields("title", "description").matching(searchContext).createQuery();
    javax.persistence.Query query  = session.createFullTextQuery(searchQuery, InventoryItem.class);

    // execute search
    List<InventoryItem> items = query.getResultList();

    tx.commit();

    return items;

}
4

1 回答 1

2

您应该可以使用 QueryBuilder 上的 bool() 方法来执行此操作。例如,要过滤返回InventoryItem的 s 使其必须属于Inventory带有 ID的 s inventoryId,您可以使用:

org.apache.lucene.search.Query searchQuery = qb.bool()
    .must(qb.keyword().onFields("title", "description").matching(searchContext).createQuery())
    .must(qb.keyword().onField("inventory.id").matching(inventoryId).createQuery())
    .createQuery();

这将在您对 s 的标题/描述的搜索与您想要匹配InventoryItem的 ID之间创建一个 AND 条件。Inventory

但是请注意,您必须注释InventoryItem.inventory@IndexedEmbedded才能包含在InventoryItem's 索引中。

于 2013-07-22T18:20:58.353 回答