Hibernate Search可以或建议在特定集合上进行关键字搜索

时间:2013-07-22 17:56:54

标签: hibernate lucene hibernate-search

我正在尝试做一个看起来像一个简单的搜索查询,但我无法找出是否有办法,如果是这样有效。

我目前正在使用hibernate和hibernate search 4.3.0。我想要做的是搜索特定的集合。例如,我有一个Inventory类,其中包含InventoryItem列表。我想执行关键字搜索,只搜索特定广告资源中的项目。是否可以将搜索限制为特定的搜索。 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;

}

1 个答案:

答案 0 :(得分:2)

您应该可以使用QueryBuilder上的bool()方法执行此操作。例如,要过滤返回的InventoryItem,使其必须属于ID为Inventory的{​​{1}},您可以使用:

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(); 的标题/说明的搜索与您想要匹配的InventoryItem的ID之间创建AND条件。

但请注意,您必须将Inventory注释为InventoryItem.inventory才能将其包含在@IndexedEmbedded的索引中。