Skip to main content

Lucene, sample JAVA code to Search an indexed file folder


Please find below the Lucene sample JAVA code to search the files inside a folder. This code will search the indexed folder for a search query in an indexed field.

This java code is expecting the index path ( where the index files were created ) , field which need to be searched and the query need be searched as program arguments like  "java SearchFiles [-index dir] [-field f] [-query string]" .


import java.io.File;
import java.util.ArrayList;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
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.FSDirectory;
import org.apache.lucene.util.Version;

public class SearchFiles {

public static void main(String[] args){
try{
String usage = "Usage: SearchFiles [-index dir] [-field f] [-query string] \n\n";
String index = "index";
String field = "contents";
String queryString = null;
int hitsPerPage = 100;
for (int i = 0; i < args.length; i++) {
if ("-index".equals(args[i])) {
index = args[i + 1];
i++;
} else if ("-field".equals(args[i])) {
field = args[i + 1];
i++;
} else if ("-query".equals(args[i])) {
queryString = args[i + 1];
i++;
}
}
new SearchFiles().searchFiles(index,field,queryString,hitsPerPage);
}catch (Exception e) {
e.printStackTrace();
}
}

public ArrayList<String> searchFiles(String index,String field,
String queryString,int hitsPerPage) throws Exception {

ArrayList<String> returnStringList = new ArrayList<String>();

IndexSearcher searcher = new IndexSearcher(FSDirectory.open(new File(index)));
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_31);
QueryParser parser = new QueryParser(Version.LUCENE_31, field, analyzer);
Query query = parser.parse(queryString);
int numberOfPages = 5;

TopDocs results = searcher.search(query, numberOfPages * hitsPerPage);

ScoreDoc[] hits = results.scoreDocs;
int numTotalHits = results.totalHits;
System.out.println(numTotalHits + " total matching documents");
returnStringList.add(numTotalHits + " total matching documents");

int start = 0;
int end = Math.min(numTotalHits, hitsPerPage);
for (int i = start; i < end; i++) {
Document doc = searcher.doc(hits[i].doc);
String path = doc.get("path");
if (path != null) {
System.out.println((i + 1) + ". " + path);
returnStringList.add((i + 1) + ". " + path);
String title = doc.get("title");
if (title != null) {
System.out.println("   Title: " + doc.get("title"));
returnStringList.add("   Title: " + doc.get("title"));
}
}
}
searcher.close();
return returnStringList;
}
}

Comments

Popular posts from this blog

Eclipse plugin: InstaSearch – for quick search

InstaSearch is an Eclipse plug-in for performing quick and advanced search of workspace files. This will index the files and when you search for some file contents, it will look with in this index and the search results will be faster, just like the Goolge instant search. It uses Lucene ( http://lucene.apache.org/ ) for indexing and fast searching of files in the workspace. Each search result file then can be previewed using few most matching and relevant lines. A double-click on the match leads to the matching line in the file. Main Features Instantly shows search results Shows a preview using relevant lines Periodically updates the index Matches partial words (e.g. case in CamelCase) Opens and highlights matches in files Searches JAR source attachments Supports filtering by extension/project/working set Download / Installation In Eclipse Helios (3.6) please install using the  Eclipse Marketplace from the Help menu http://marketplace.eclipse.org/s...

Google Chrome shortcut keys

If you are a Google Chromey guy, please find below the list of shortcut keys for some of the most used features  :-) Find more shortcut keys @  http://www.google.com/support/chrome/bin/static.py?page=guide.cs&guide=25799&topic=28650

Jsp and CSS size limits that web developers need to aware

Here I am listing some erroneous cases that might occur in your web development phase, due to some size restrictions. JSP file size limit : You might get some run time exceptions that the JSP file size limit exceeds. Please find below the reason : In JVM the size of a single JAVA method is limited to 64kb. When the jsp file is converted to Servlet, if the jspservice method's size exceeds the 64kb limit, this exception will occur. Keep in mind that this exception depends on the implementation of the JSP translator, means the same JSP code may give an exception in Tomcat and may run successfully in Weblogic due to the the difference in the logic to built the Servlet methods from JSP. The best way to omit this issue is by using dynamic include.For example, if you are using                  <%@ include file="sample.jsp" %> (static include),  replace this to               ...

ATG and XML File Combination

              An XML file might appear at several points in the CONFIGPATH. The ATG platform, at runtime,   automatically combines all the XML files in the CONFIGPATH with the same name into a single composite file, which is then used by the appropriate component.               XML files are combined one tag at a time: in other words, tags are matched up, and the combination rules are applied to each pair of matched tags. XML file combination is controlled with an XML attribute named xml-combine. This attribute is used only in the preprocessing stage of XML file combination. The xml-combine attribute can have the following values: xml-combine = "replace" xml-combine = "remove" xml-combine = "append" xml-combine = "append-without-matching" -->  This is the same as  xml-combine="append" , except that embedded tags are not matched and combined recursively. The content is simply appended. ...

ATG Search - how to create a search project

Here I am going to explain how we can create a new ATG search project. It involves 3 steps --> Specify the general search project settings, Specify the content of search indexing and Build the index. Below I am elaborating the different steps involved with screen shots : 1. Go to Search Project Administration ui @  BCC and Click the button "New Search Project" to create a new search project. 2. Specify the search project name, give description and click the button "Create Search Project". 3. Click the button "Add Content" to add the search project content. 4. Specify the content name, select the content type and specify the IndexingOutputConfig path if the content type is ATG repository. Specify the remote host and port if you are using another server for fetching the content. 5. Click the content in the left side and expand the advanced option to specify the language and other customizations. 6. Click the ...