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"; 
    } 

回答

0

文檔代表的是

從Java Lucene的第一個也是最顯著差異是通過所有字段默認搜索條款。

如果你想使用LuceneSearch\QueryParser::parse()方法,你可以準備$userQueryString這樣的:

$userQueryString = 'name:search input query string description:search input query string'; 

您也可以使用Zend\Search\Lucene\Search\Query\MultiTerm::addTerm()方法是這樣的:

... 
$userQuery = new Zend\Search\Lucene\Search\Query\MultiTerm(); 
$userQuery->addTerm(new Zend\Search\Lucene\Index\Term($userQueryString, 'name')); 
$userQuery->addTerm(new Zend\Search\Lucene\Index\Term($userQueryString, 'description')); 
... 
$query->addSubquery($userQuery, true /* required */);