【问题标题】:php lucene how to update and delete rows in index filephp lucene如何更新和删除索引文件中的行
【发布时间】:2011-02-28 14:21:45
【问题描述】:

用户有时会更改帖子的内容,实际数据库中的内容字段会更新。

我怎样才能获得索引文件更新的相同字段?

当用户删除帖子时,我如何在索引文件中删除该帖子?

【问题讨论】:

    标签: php zend-framework search lucene


    【解决方案1】:

    我在 Symfony 中使用了 lucene 搜索,下面是我的使用方法:

    // Called when an object is saved
    public function save(Doctrine_Connection $conn = null) {
        $conn = $conn ? $conn : $this->getTable()->getConnection();
        $conn->beginTransaction();
        try {
            $ret = parent::save($conn);
    
            $this->updateLuceneIndex();
    
            $conn->commit();
    
            return $ret;
        } catch (Exception $e) {
            $conn->rollBack();
            throw $e;
        }
    }
    
    public function updateLuceneIndex() {
        $index = $this->getTable()->getLuceneIndex();
    
        // remove existing entries
        foreach ($index->find('pk:' . $this->getId()) as $hit) {
            $index->delete($hit->id);
        }
    
        $doc = new Zend_Search_Lucene_Document();
    
        // store job primary key to identify it in the search results
        $doc->addField(Zend_Search_Lucene_Field::UnIndexed('pk', $this->getId()));
    
        // index job fields
        $doc->addField(Zend_Search_Lucene_Field::unStored('title', Utils::stripAccent($this->getTitle()), 'utf-8'));
        $doc->addField(Zend_Search_Lucene_Field::unStored('summary', Utils::stripAccent($this->getSummary()), 'utf-8'));
    
        // add job to the index
        $index->addDocument($doc);
        $index->commit();
    }
    
    // Called when an object is deleted
    public function delete(Doctrine_Connection $conn = null) {
        $index = $this->getTable()->getLuceneIndex();
    
        foreach ($index->find('pk:' . $this->getId()) as $hit) {
            $index->delete($hit->id);
        }
    
        return parent::delete($conn);
    }
    

    这是我获取索引的方式:

    public static function getInstance() {
        return Doctrine_Core::getTable('Work');
    }
    
    static public function getLuceneIndexFile() {
        return sfConfig::get('sf_data_dir') . '/indexes/work.' . sfConfig::get('sf_environment') . '.index';
    }
    
    static public function getLuceneIndex() {
        ProjectConfiguration::registerZend();
    
        if (file_exists($index = self::getLuceneIndexFile())) {
    
            return Zend_Search_Lucene::open($index);
        } else {
            return Zend_Search_Lucene::create($index);
        }
    }
    

    希望对你有所帮助;)

    【讨论】:

    • 我对此代码有一个小问题。如何在未索引的字段中使用 find()?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多