Lucene-first-application
Lucene-最初のアプリケーション
この章では、Lucene Frameworkを使用した実際のプログラミングについて学習します。 Luceneフレームワークを使用して最初の例を書き始める前に、リンク:/lucene/lucene_environment [Lucene-Environment Setup]チュートリアルで説明されているように、Lucene環境を適切にセットアップしていることを確認する必要があります。 Eclipse IDEの実用的な知識があることが推奨されます。
ここで、見つかった検索結果の数を出力する簡単な検索アプリケーションを作成します。 このプロセス中に作成されたインデックスのリストも表示されます。
ステップ1-Javaプロジェクトの作成
最初のステップは、Eclipse IDEを使用して簡単なJavaプロジェクトを作成することです。 File> New→ Project オプションに従い、最後にウィザードリストから Java Project ウィザードを選択します。 次のようにウィザードウィンドウを使用して、プロジェクトに LuceneFirstApplication という名前を付けます-
プロジェクトが正常に作成されると、次のコンテンツが Project Explorer に表示されます-
Lucene First Application Directories
ステップ2-必要なライブラリを追加する
プロジェクトにLuceneコアフレームワークライブラリを追加しましょう。 これを行うには、プロジェクト名 LuceneFirstApplication を右クリックし、コンテキストメニューで使用可能な次のオプションに従います。*ビルドパス→ビルドパスの設定*を使用して、Javaビルドパスウィンドウを表示します-
- ライブラリ*タブにある*外部JARを追加*ボタンを使用して、Luceneインストールディレクトリから次のコアJARを追加します-
- lucene-core-3.6.2
手順3-ソースファイルの作成
*LuceneFirstApplication* プロジェクトの下に実際のソースファイルを作成しましょう。 まず、* com.finddevguides.lucene。*というパッケージを作成する必要があります。これを行うには、パッケージエクスプローラーのセクションでsrcを右クリックし、オプション[*新規->パッケージ*]に従います。
次に、 com.finddevguides.lucene パッケージの下に LuceneTester.java およびその他のJavaクラスを作成します。
LuceneConstants.java
このクラスは、サンプルアプリケーション全体で使用されるさまざまな定数を提供するために使用されます。
package com.finddevguides.lucene;
public class LuceneConstants {
public static final String CONTENTS = "contents";
public static final String FILE_NAME = "filename";
public static final String FILE_PATH = "filepath";
public static final int MAX_SEARCH = 10;
}
TextFileFilter.java
このクラスは、*。txtファイル*フィルターとして使用されます。
package com.finddevguides.lucene;
import java.io.File;
import java.io.FileFilter;
public class TextFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".txt");
}
}
Indexer.java
このクラスは、Luceneライブラリを使用して検索可能にするために、生データにインデックスを付けるために使用されます。
package com.finddevguides.lucene;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class Indexer {
private IndexWriter writer;
public Indexer(String indexDirectoryPath) throws IOException {
//this directory will contain the indexes
Directory indexDirectory =
FSDirectory.open(new File(indexDirectoryPath));
//create the indexer
writer = new IndexWriter(indexDirectory,
new StandardAnalyzer(Version.LUCENE_36),true,
IndexWriter.MaxFieldLength.UNLIMITED);
}
public void close() throws CorruptIndexException, IOException {
writer.close();
}
private Document getDocument(File file) throws IOException {
Document document = new Document();
//index file contents
Field contentField = new Field(LuceneConstants.CONTENTS, new FileReader(file));
//index file name
Field fileNameField = new Field(LuceneConstants.FILE_NAME,
file.getName(),Field.Store.YES,Field.Index.NOT_ANALYZED);
//index file path
Field filePathField = new Field(LuceneConstants.FILE_PATH,
file.getCanonicalPath(),Field.Store.YES,Field.Index.NOT_ANALYZED);
document.add(contentField);
document.add(fileNameField);
document.add(filePathField);
return document;
}
private void indexFile(File file) throws IOException {
System.out.println("Indexing "+file.getCanonicalPath());
Document document = getDocument(file);
writer.addDocument(document);
}
public int createIndex(String dataDirPath, FileFilter filter)
throws IOException {
//get all files in the data directory
File[] files = new File(dataDirPath).listFiles();
for (File file : files) {
if(!file.isDirectory()
&& !file.isHidden()
&& file.exists()
&& file.canRead()
&& filter.accept(file)
){
indexFile(file);
}
}
return writer.numDocs();
}
}
Searcher.java
このクラスは、インデクサーによって作成されたインデックスを検索して、要求されたコンテンツを検索するために使用されます。
package com.finddevguides.lucene;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
public class Searcher {
IndexSearcher indexSearcher;
QueryParser queryParser;
Query query;
public Searcher(String indexDirectoryPath)
throws IOException {
Directory indexDirectory =
FSDirectory.open(new File(indexDirectoryPath));
indexSearcher = new IndexSearcher(indexDirectory);
queryParser = new QueryParser(Version.LUCENE_36,
LuceneConstants.CONTENTS,
new StandardAnalyzer(Version.LUCENE_36));
}
public TopDocs search( String searchQuery)
throws IOException, ParseException {
query = queryParser.parse(searchQuery);
return indexSearcher.search(query, LuceneConstants.MAX_SEARCH);
}
public Document getDocument(ScoreDoc scoreDoc)
throws CorruptIndexException, IOException {
return indexSearcher.doc(scoreDoc.doc);
}
public void close() throws IOException {
indexSearcher.close();
}
}
LuceneTester.java
このクラスは、luceneライブラリのインデックス作成と検索機能をテストするために使用されます。
package com.finddevguides.lucene;
import java.io.IOException;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
public class LuceneTester {
String indexDir = "E:\\Lucene\\Index";
String dataDir = "E:\\Lucene\\Data";
Indexer indexer;
Searcher searcher;
public static void main(String[] args) {
LuceneTester tester;
try {
tester = new LuceneTester();
tester.createIndex();
tester.search("Mohan");
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
private void createIndex() throws IOException {
indexer = new Indexer(indexDir);
int numIndexed;
long startTime = System.currentTimeMillis();
numIndexed = indexer.createIndex(dataDir, new TextFileFilter());
long endTime = System.currentTimeMillis();
indexer.close();
System.out.println(numIndexed+" File indexed, time taken: "
+(endTime-startTime)+" ms");
}
private void search(String searchQuery) throws IOException, ParseException {
searcher = new Searcher(indexDir);
long startTime = System.currentTimeMillis();
TopDocs hits = searcher.search(searchQuery);
long endTime = System.currentTimeMillis();
System.out.println(hits.totalHits +
" documents found. Time :" + (endTime - startTime));
for(ScoreDoc scoreDoc : hits.scoreDocs) {
Document doc = searcher.getDocument(scoreDoc);
System.out.println("File: "
+ doc.get(LuceneConstants.FILE_PATH));
}
searcher.close();
}
}
ステップ4-データとインデックスのディレクトリ作成
record1.txtからrecord10.txtまでの学生の名前やその他の詳細を含む10個のテキストファイルを使用し、それらを E:\ Lucene \ Data ディレクトリに配置しました。 link:/lucene/data.zip [テストデータ]。 インデックスディレクトリパスは、 E:\ Lucene \ Index として作成する必要があります。 このプログラムを実行すると、そのフォルダーに作成されたインデックスファイルのリストを見ることができます。
ステップ5-プログラムの実行
ソース、生データ、データディレクトリ、インデックスディレクトリの作成が完了したら、プログラムをコンパイルして実行する準備が整います。 これを行うには、 LuceneTester.Java ファイルタブをアクティブのままにし、Eclipse IDEで使用可能な Run オプションを使用するか、 Ctrl + F11 を使用して LuceneTester アプリケーションをコンパイルおよび実行します。 アプリケーションが正常に実行されると、Eclipse IDEのコンソールに次のメッセージが出力されます-
Indexing E:\Lucene\Data\record1.txt
Indexing E:\Lucene\Data\record10.txt
Indexing E:\Lucene\Data\record2.txt
Indexing E:\Lucene\Data\record3.txt
Indexing E:\Lucene\Data\record4.txt
Indexing E:\Lucene\Data\record5.txt
Indexing E:\Lucene\Data\record6.txt
Indexing E:\Lucene\Data\record7.txt
Indexing E:\Lucene\Data\record8.txt
Indexing E:\Lucene\Data\record9.txt
10 File indexed, time taken: 109 ms
1 documents found. Time :0
File: E:\Lucene\Data\record4.txt
プログラムを正常に実行すると、次のコンテンツが* indexディレクトリ*にあります-