import org.apache.lucene.document.*;import org.apache.lucene.index.*;import com.infosys.lucene.code.JavaParser.*;public class JavaSourceCodeIndexer { private static JavaParser parser = new JavaParser(); private static final String IMPLEMENTS = "implements"; private static final String IMPORT = "import"; ... public static void main(String[] args) { File indexDir = new File("C:\\Lucene\\Java"); File dataDir = new File("C:\\JavaSourceCode "); IndexWriter writer = new IndexWriter(indexDir, new JavaSourceCodeAnalyzer(), true); indexDirectory(writer, dataDir); writer.close(); } public static void indexDirectory(IndexWriter writer, File dir){ File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { File f = files[i]; // Create a Lucene Document Document doc = new Document(); // Use JavaParser to parse file parser.setSource(f); addImportDeclarations(doc, parser); addComments(doc, parser); // Extract Class elements Using Parser JClass cls = parser.getDeclaredClass(); addClass(doc, cls); // Add field to the Lucene Document doc.add(Field.UnIndexed(FILENAME, f.getName())); writer.addDocument(doc); } } private static void addClass(Document doc, JClass cls) { //For each class add Class Name field doc.add(Field.Text(CLASS, cls.className)); String superCls = cls.superClass; if (superCls != null) //Add the class it extends as extends field doc.add(Field.Text(EXTENDS, superCls)); // Add interfaces it implements ArrayList interfaces = cls.interfaces; for (int i = 0; i < interfaces.size(); i++) doc.add(Field.Text(IMPLEMENTS, (String) interfaces.get(i))); //Add details on methods declared addMethods(cls, doc); ArrayList innerCls = cls.innerClasses; for (int i = 0; i < innerCls.size(); i++) addClass(doc, (JClass) innerCls.get(i)); } private static void addMethods(JClass cls, Document doc) { ArrayList methods = cls.methodDeclarations; for (int i = 0; i < methods.size(); i++) { JMethod method = (JMethod) methods.get(i); // Add method name field doc.add(Field.Text(METHOD, method.methodName)); // Add return type field doc.add(Field.Text(RETURN, method.returnType)); ArrayList params = method.parameters; for (int k = 0; k < params.size(); k++) // For each method add parameter types doc.add(Field.Text(PARAMETER, (String)params.get(k))); String code = method.codeBlock; if (code != null) //add the method code block doc.add(Field.UnStored(CODE, code)); } } private static void addImportDeclarations(Document doc, JavaParser parser) { ArrayList imports = parser.getImportDeclarations(); if (imports == null) return; for (int i = 0; i < imports.size(); i++) //add import declarations as keyword doc.add(Field.Keyword(IMPORT, (String) imports.get(i))); }}
Lucene有四種不同的欄位類型:Keyword,UnIndexed,UnStored和Text,用於指定建立最佳索引。
Keyword欄位是指不需要分析器解析但需要被編入索引並儲存到索引中的部分。JavaSourceCodeIndexer類使用該欄位來儲存匯入類的聲明。
UnIndexed欄位是既不被分析也不被索引,但是要被逐字逐句的將其值儲存到索引中。由於我們一般要隱藏檔的位置但又很少用檔案名稱作為關鍵字來搜尋,所以用該欄位來索引Java檔案名稱。
UnStored欄位和UnIndexed欄位相反。該類型的Field要被分析並編入索引,但其值不會被儲存到索引中。由於儲存方法的全部原始碼需要大量的空間。所以用UnStored欄位來儲存被索引的方法原始碼。可以直接從Java源檔案中取出方法的原始碼,這樣作可以控制我們的索引的大小。
Text欄位在索引過程中是要被分析、索引並儲存的。類名是作為Text欄位來儲存。下表展示了JavaSourceCodeIndexer類使用Field欄位的一般情況。
1.
用Lucene建立的索引可以用Luke預覽和修改,Luke是用於理解索引很有用的一個開源工具。圖1中是Luke工具的一張,它顯示了JavaSourceCodeIndexer類建立的索引。
圖1:在Luke中索引
所見,匯入類的聲明沒有標記化或分析就被儲存了。類名和方法名被轉換為小寫字母后,才儲存的。
查詢Java原始碼
建立多欄位索引後,可以使用Lucene來查詢這些索引。它提供了這兩個重要類分別是IndexSearcher和QueryParser,用於搜尋檔案。QueryParser類則用於解析由使用者輸入的查詢運算式,同時IndexSearcher類在檔案中搜尋滿足查詢條件的結果。下列表格顯示了一些可能發生的查詢及它的含義:
使用者通過索引不同的文法元素組成有效查詢條件並搜尋代碼。下面列出了用於搜尋的範例程式碼。
public class JavaCodeSearch {public static void main(String[] args) throws Exception{ File indexDir = new File(args[0]); String q = args[1]; //parameter:JGraph code:insert Directory fsDir = FSDirectory.getDirectory(indexDir,false); IndexSearcher is = new IndexSearcher(fsDir); PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper( new JavaSourceCodeAnalyzer()); analyzer.addAnalyzer("import", new KeywordAnalyzer()); Query query = QueryParser.parse(q, "code", analyzer); long start = System.currentTimeMillis(); Hits hits = is.search(query); long end = System.currentTimeMillis(); System.err.println("Found " + hits.length() + " docs in " + (end-start) + " millisec"); for(int i = 0; i < hits.length(); i++){ Document doc = hits.doc(i); System.out.println(doc.get("filename") + " with a score of " + hits.score(i)); } is.close();}}
IndexSearcher執行個體用FSDirectory來開啟包含索引的目錄。然後使用Analyzer執行個體分析搜尋用的查詢字串,以確保它與索引(還原詞根,轉換小寫字母,過濾掉,等等)具有同樣的形式。為了避免在查詢時將Field作為一個關鍵字索引,Lucene做了一些限制。Lucene用Analyzer分析在QueryParser執行個體裡傳給它的所有欄位。為瞭解決這個問題,可以用Lucene提供的PerFieldAnalyzerWrapper類為查詢中的每個欄位指定必要的分析。因此,查詢字串import:org.w3c.*
AND code:Document將用KeywordAnalyzer來解析字串org.w3c.*並且用JavaSourceCodeAnalyzer來解析Document。QueryParser執行個體如果查詢沒有與之相符的欄位,就使用預設的欄位:code,使用PerFieldAnalyzerWrapper來分析查詢字串,並返回分析後的Query執行個體。IndexSearcher執行個體使用Query執行個體並返回一個Hits執行個體,它包含了滿足查詢條件的檔案。
結束語
這篇文章介紹了Lucene——文本搜尋引擎,其可以通過載入分析器及多欄位索引來實現原始碼搜尋。文章只介紹了程式碼搜尋引擎的準系統,同時在源碼檢索中使用愈加完善的分析器可以提高檢索效能並獲得更好的查詢結果。這種搜尋引擎可以允許使用者在軟體開發社區搜尋和共用原始碼。