0
我使用ZF2搜索Lucene搜索網站上的產品。 我需要使用用戶的輸入文本搜索產品,並通過多個參數(例如類別和類型ID)篩選結果。 但是問題在於用戶的輸入是在所有字段中搜索的,我只需要在名稱和描述字段中搜索。Zend Lucene僅在指定字段中使用篩選器搜索
下面是將產品添加到索引代碼:
$index = Lucene::create('./data/index');
$products = $this->getEntityManager()->getRepository('Application\Entity\Product')->findAll();
foreach ($products as $product) {
echo "Adding ".$product->getName(). " to index\n";
$doc = new LuceneDocument();
$doc->addField(LuceneDocument\Field::keyword('type', 'product'));
$doc->addField(LuceneDocument\Field::keyword('product_id', (string)$product->getId()));
$doc->addField(LuceneDocument\Field::keyword('category_id', (string)$product->getCategory()->getId()));
$fieldName = LuceneDocument\Field::text('product_name', $product->getName());
$fieldName->boost = 2.0; // Field weight
$doc->addField($fieldName);
$fieldDescription = LuceneDocument\Field::unStored('product_description', $product->getDescription());
$fieldDescription->boost = 1.0; // Field weight
$doc->addField($fieldDescription);
$index->addDocument($doc);
}
$index->commit();
代碼搜索:
$userQueryString = 'search input query string';
$userQuery = LuceneSearch\QueryParser::parse($userQueryString);
// how to limit userQuery to search only in specific fields?
$typeTerm = new LuceneIndex\Term('product', 'type');
$typeQuery = new LuceneSearch\Query\Term($typeTerm);
$categoryTerm = new LuceneIndex\Term(5, 'category_id');
$categoryQuery = new LuceneSearch\Query\Term($categoryTerm);
$query = new LuceneSearch\Query\Boolean();
$query->addSubquery($typeQuery, true /* required */);
$query->addSubquery($categoryQuery, true /* required */);
$query->addSubquery($userQuery, true /* required */);
$index = Lucene::open('./data/index');
$hits = $index->find($query);
foreach ($hits as $hit) {
echo "Type: ".$hit->type."\n";
echo "Id: ".$hit->product_id."\n";
echo "Name: ".$hit->product_name."\n";
echo "Category: ".$hit->category_id."\n";
echo "\n";
}