Skip to main content

lucene example

In simple words: it parses a text and without saving the text the framework can search inside it. It keeps track of terms used inside the text. Of course you can optionally save the text into your <a href="http://www.phloxblog.in/lucene-indexing-and-searching-in-multiple-tables-conceptuual-representaion/" data-cke-saved-href="http://www.phloxblog.in/lucene-indexing-and-searching-in-multiple-tables-conceptuual-representaion/">lucene index</a>.

 Lets take an example.

 I have created a database and a table named it 'city'.

 create table `city` (

 `id` bigint (20),

 `city_name` varchar (765)

 );

 Now I have added two record Kolkata,Delhi in the database.

 Now create a java project and add lucene-analyzers-common-4.0.0.jar,lucene-core-4.0.0.jar,lucene-queries-4.0.0.jar,lucene-queryparser-4.0.0.jar and mysql-connector-java-5.1.22-bin.jar in the project.

 create a java class named LuceneTest  and write the following.

 LuceneTest .java


 package com.test;

 import java.io.IOException;

 import java.sql.Connection;

 import java.sql.DriverManager;

 import java.sql.ResultSet;

 import java.sql.Statement;

 import org.apache.lucene.analysis.standard.StandardAnalyzer;

 import org.apache.lucene.document.Document;

 import org.apache.lucene.document.Field;

 import org.apache.lucene.document.StringField;

 import org.apache.lucene.document.TextField;

 import org.apache.lucene.index.DirectoryReader;

 import org.apache.lucene.index.IndexReader;

 import org.apache.lucene.index.IndexWriter;

 import org.apache.lucene.index.IndexWriterConfig;

 import org.apache.lucene.queryparser.classic.ParseException;

 import org.apache.lucene.queryparser.classic.QueryParser;

 import org.apache.lucene.search.IndexSearcher;

 import org.apache.lucene.search.Query;

 import org.apache.lucene.search.ScoreDoc;

 import org.apache.lucene.search.TopScoreDocCollector;

 import org.apache.lucene.store.Directory;

 import org.apache.lucene.store.RAMDirectory;

 import org.apache.lucene.util.Version;

 public class LuceneTest {


 /**

 * @param args

 */

 public static void main(String[] args) throws IOException, ParseException{

 StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);

 String dbUrl = "jdbc:mysql://" + "localhost:3306" + "/" + "mydatabase";

 String dbClass = "com.mysql.jdbc.Driver";

 Connection conn = null;

 // 1. create the index

 Directory index = new RAMDirectory();

 IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_40, analyzer);

 IndexWriter w = new IndexWriter(index, config);

 //Connect to MySQL:

 try

 {

 Class.forName(dbClass);

 conn = DriverManager.getConnection (dbUrl, "root", "liferay");

 Statement stmt= conn.createStatement();

 String sql = "select * from city" ;

 ResultSet rs = stmt.executeQuery(sql);

 while (rs.next()) {

 Document doc = new Document();

 doc.add(new Field("id", rs.getString("id"), Field.Store.YES, Field.Index.ANALYZED));

 doc.add(new Field("city_name", rs.getString("city_name"), Field.Store.YES, Field.Index.ANALYZED));

 w.addDocument(doc);

 }

 }

 catch (Exception e) {

 // TODO: handle exception

 }

 finally{

 w.close();

 }

 // 2. query

 String querystring = args.length &gt; 0 ? args[0] : "kolkata";

 // the "title" arg specifies the default field to use

 // when no field is explicitly specified in the query.

 Query q = new QueryParser(Version.LUCENE_40, "city_name", analyzer).parse(querystring);

 // 3. search

 int hitsPerPage = 10;

 IndexReader reader = DirectoryReader.open(index);

 IndexSearcher searcher = new IndexSearcher(reader);

 TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);

 searcher.search(q, collector);

 ScoreDoc[] hits = collector.topDocs().scoreDocs;

 // 4. display results

 System.out.println("Found " + hits.length + " hits.");

 for(int i=0;i&lt;hits.length;++i) {

 System.out.println("------"+hits[i].score);

 int docId = hits[i].doc;

 Document d = searcher.doc(docId);

 System.out.println((i + 1) + ". " + d.get("city_name"));

 }

 reader.close();

 }

 private static void addDoc(IndexWriter w, String title, String isbn) throws IOException {

 Document doc = new Document();

 doc.add(new TextField("title", title, Field.Store.YES));

 // use a string field for isbn because we don't want it tokenized

 doc.add(new StringField("isbn", isbn, Field.Store.YES));

 w.addDocument(doc);

 }

 }

 Now run the program.

Comments

Popular posts from this blog

jdbc mysql example in java

Here’s an example to show you how to connect to MySQL database via a JDBC driver.To connect to MySQL from Java, you have to use the JDBC driver from MySQL. You find the latest MySQL JDBC driver under the following URL:http://dev.mysql.com/downloads/connector/j.
Create a example database and named it test.Now create a a table name it user. Create table user ((userid INT NOT NULL AUTO_INCREMENT,
username VARCHAR(30) NOT NULL, PRIMARY KEY (userid)); Now add the record in your table; Now create a project in eclipse and mysql-connector jar in its classpath.package com.test;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; publicclass JavaJDBCExample { private Connection connect = null; private Statement statement = null; private ResultSet resultSet = null; publicvoid readDatabase() { try { // this will load the MySQL driver Class.forName("com.mysql.jdbc.Driver"); // setup the connection wi…

singleton design pattern

Java Singleton design pattern is one of the design pattern which suggest that only one instance of a Singleton object is created by the JVM. This is useful when exactly one object is needed to coordinate actions across the system Example: public class Singleton{ privatestatic Singleton singleton = null; private Singleton(){ } publicstaticsynchronized Singleton getInstance( ) { if(singleton == null) { singleton = new Singleton(); } returnsingleton; } publicvoid test( ) { System.out.println("test"); } @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub returnnew CloneNotSupportedException(); } } publicclass SingletonTest { publicstaticvoid main(String[] args){ Singleton singleton = Singleton.getInstance(); try{ Singleton

Tomcat configuration

1. How to deploy web application in tomcat 
 Create a war file and deploy it in tomcat->webapps folder.Restart tomcat and write localhost:8080/YOURWEBAPPNAME. 
 2. Add jndi in tomcat 
 <Context>
 <Resource name="jdbc/myDB" auth="Container"
 type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000"
 username="admin" password="admin"
 driverClassName="com.mysql.jdbc.Driver"
 url="jdbc:mysql://localhost:3306/javatest"/> 
 </Context>
 in web.xml 
 <resource-ref>
 <description>DB Connection</description>
 <res-ref-name>jdbc/myDB</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
 </resource-ref> 
 3. Add user with manager role in tomcat   Tomcat-users.xml 
 <tomcat-users>
 <role rolename="manager"/>
 <user username="admin"…