php引入lucene搜索引擎方法.

 1、lucene包的下載地址:http://apache.etoak.com/lucene/java/3.3.0/

2、下載jdk環境

3、下載JavaBridge URL:http://sourceforge.net/projects/php-java-bridge/

步驟:

1安裝好jdk

2下載的JavaBridge.jar拷到php的ext 文件夾下.

3用rar壓縮軟件打開javaBridge.jar找到java文件夾,該文件夾下大都是後綴是.inc格式文件.把java整個考到www/php_java/下.

4雙擊javaBridge.jar打開8080端口

5在php_java下寫php測試文件

<?php

require_once("java/Java.inc");

header("content-type:text/html; charset=utf-8");
// get instance of Java class java.lang.System in PHP
$system = new Java('java.lang.System');
$s = new Java("java.lang.String", "php-java-bridge config...<br><br>");
echo $s;

// demonstrate property access
print 'Java version='.$system->getProperty('java.version').' <br>';
print 'Java vendor=' .$system->getProperty('java.vendor').' <br>';
print 'OS='.$system->getProperty('os.name').' '.
$system->getProperty('os.version').' on '.
$system->getProperty('os.arch').' <br>';

// java.util.Date example
$formatter = new Java('java.text.SimpleDateFormat',
"EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");

print $formatter->format(new Java('java.util.Date'));
?>

結果:

php-java-bridge config...

Java version=1.6.0_10-rc2
Java vendor=Sun Microsystems Inc.
OS=Windows XP 5.1 on x86
星期五, 八月 12, 2011 at 9:38:16 上午 中國標準時間Java version=1.6.0_10-rc2

用eclipse寫一個TestLucene包類命名爲TxtFileIndexer.java 

package TestLucene;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.util.Date;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.FSDirectory;

public class TxtFileIndexer ...{

    public String test() ...{
        return "test is ok hohoho";
    }

    /**//**
     * @param args
     */
    public String createIndex(String indexDir_path,String dataDir_path) throws Exception ...{
        String result = "";
        File indexDir = new File(indexDir_path);
        File dataDir = new File(dataDir_path);
        Analyzer luceneAnalyzer = new StandardAnalyzer();
        File[] dataFiles = dataDir.listFiles();
        IndexWriter indexWriter = new IndexWriter(indexDir,luceneAnalyzer,true);
        long startTime = new Date().getTime();
        for(int i=0; i < dataFiles.length; i++) ...{
            if(dataFiles[i].isFile() && dataFiles[i].getName().endsWith(".html")) ...{
                result += "Indexing file" + dataFiles[i].getCanonicalPath()+"<br />";
                Document document = new Document();
                Reader txtReader = new FileReader(dataFiles[i]);
                document.add(Field.Text("path",dataFiles[i].getCanonicalPath()));
                document.add(Field.Text("contents",txtReader));
                indexWriter.addDocument(document);
            }
        }

        indexWriter.optimize();
        indexWriter.close();
        long endTime = new Date().getTime();

        result += "It takes"+(endTime-startTime)
                + " milliseconds to create index for the files in directory "
                + dataDir.getPath();
        return result;
    }

    public String searchword(String ss,String index_path)  throws Exception  ...{
        String queryStr = ss;
        String result = "Result:<br />";
        //This is the directory that hosts the Lucene index
        File indexDir = new File(index_path);
        FSDirectory directory = FSDirectory.getDirectory(indexDir,false);
        IndexSearcher searcher = new IndexSearcher(directory);
        if(!indexDir.exists())...{
            result = "The Lucene index is not exist";
            return result;
        }
        Term term = new Term("contents",queryStr.toLowerCase());
        TermQuery luceneQuery = new TermQuery(term);
        Hits hits = searcher.search(luceneQuery);
        for(int i = 0; i < hits.length(); i++)...{
            Document document = hits.doc(i);
            result += "<br /><a href='getfile.php?w="+ss+"&f="+document.get("path")+"'>File: " + document.get("path")+"</a>\n";
        }
        return result;
    }

}


先創建一個我們寫的TxtFileIndexer類的實例,

$tf = new Java('TestLucene.TxtFileIndexer'); 

然後就按正常PHP類的調用方法的方式進行調用,首先創建索引:

$data_path = "F:/test/php_lucene/htdocs/data/manual"; //定義被索引內容的目錄 
$index_path = "F:/test/php_lucene/htdocs/data/search"; //定義生成的索引文件存放目錄 
$s = $tf->createIndex($index_path,$data_path); //調用Java類的方法 
print $s; //打印返回的結果 


 

$index_path = "F:/test/php_lucene/htdocs/data/search"; //定義生成的索引文件存放目錄 
$s = $tf->searchword("here is keyword for search",$index_path);
print $s; 
java_require("F:/test/php_lucene/htdocs/lib/"); //這是個例子,我的類和Lucene都放到這個目錄下,這樣就可以了,是不是很簡單。 
測試代碼
<?php

    error_reporting(0);

    java_require("F:/test/php_lucene/htdocs/lib/");

    $tf = new Java('TestLucene.TxtFileIndexer');
    $s = $tf->test();
    print "TestLucene.TxtFileIndexer->test()<br />".$s;
    echo "<hr />";

    $data_path = "F:/test/php_lucene/htdocs/data/manual";
    $index_path = "F:/test/php_lucene/htdocs/data/search";

    if(
{1}

GET["action"] == "create") ...{ $s = $tf->createIndex($index_path,$data_path); print $s; }else ...{ echo "<form method=get> <input type=text name=w /><input type=submit value=search /><br />"; if(
{1}

GET["w"] != "") ...{ $s = $tf->searchword(
{1}

GET["w"],$index_path); print $s; } }?>



轉載:http://www.lucene.com.cn/php.htm
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章