Zend Lucene仅在带有过滤器的指定字段中搜索

时间:2014-06-23 07:09:37

标签: php zend-framework lucene zend-framework2 zend-search-lucene

我使用ZF2搜索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";
    }

1 个答案:

答案 0 :(得分: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 */);