发新话题
打印

Zend_Search_Lucene更新Index的方法

Zend_Search_Lucene更新Index的方法

在使用Zend Framework的Search_Lucene模块时,假设你有个文档已经加入到索引里面了,而这个文档后来被删除或者被修改了,需要及时更新索引才能保证数据的时效性,以前比较傻的办法就是全部重新创建一次索引,这个开销很大,也不适合大型应用,典型的场景就是论坛的帖子,如果帖子被删除或者修改了,就需要即使更新索引。

  Zend_Search_Lucene官方文档关于删除和更新一个索引的说明实在太少,我自己琢磨了个简单的办法来实现,大家可以尝试一下,也许有更好的办法,知道的朋友可以告知我。

  下面是官方文档的说明:
复制内容到剪贴板
代码:
<?php
$removePath = ...;
$hits = $index->find('path:' . $removePath);
foreach ($hits as $hit) {
    $index->delete($hit->id);
}
?>
  

    这里头困惑的是$removePath这个东西,我是没有明白咋回事,下面说说我用的办法。

  首先,假设我们的文档text都有个唯一的tid字段,那么我们就根据这个tid来作为每次删除和更新的依据,由于Lucene创建索引的时候,(我自己测试的)用数字类型无法成为keyword并且作为索引的字段,于是我们需要转换为字符串,这里我通过md5的方式把tid变成唯一的字符串,通过这个字符串来找到需要删除和更新的索引内容。
复制内容到剪贴板
代码:
//创建索引的时候,部分代码:
$index = Zend_Search_Lucene::create($this->lucne_index); //我类内部表示index路径的变量
$doc = new Zend_Search_Lucene_Document();
Zend_Search_Lucene_Analysis_Analyzer::setDefault(
    new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8()); //根据你自己需要配置字符集

$doc->addField(Zend_Search_Lucene_Field::UnStored('key', md5($tid)));
$doc->addField(Zend_Search_Lucene_Field::Text('title', $title));
$doc->addField(Zend_Search_Lucene_Field::UnStored('content', $content));

$index->addDocument($doc);
$index->commit();

//删除和更新索引的部分代码:
//先删除之
$key = md5($tid);
$index = Zend_Search_Lucene::open($this->lucne_index);
$query = Zend_Search_Lucene_Search_QueryParser::parse("key:$key", 'utf-8');
$hits = $index->find($query);
foreach ($hits AS $hit) {
    $index->delete($hit->id);
}
//重新索引更新后的数据,代码和创建一样
$doc->addField(Zend_Search_Lucene_Field::UnStored('key', md5($tid)));
$doc->addField(Zend_Search_Lucene_Field::Text('title', $title));
$doc->addField(Zend_Search_Lucene_Field::UnStored('content', $content));

$index->addDocument($doc);
$index->commit();
  其实思路就是先找到要更新的内容,删之,然后把新的数据重新添加到索引。

  抛砖引玉,欢迎交流。
一個偽裝成白癡的天纔!

TOP

发新话题