我正在尝试做一个看似简单的搜索查询,但无法确定是否有办法,如果有,是否有效。
我目前正在使用带有休眠搜索 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;
}