lucene-java-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Ian Lea <>
Subject Re: Database Example
Date Tue, 20 Nov 2001 09:44:12 GMT
> I'm new to Lucene, does any one have any good samples or links to tutorial sites?

You can find a tutorial at
> I'm particularlly interested in the ability to index a database.

Someone asked a similar question a week or so back and I posted the
reply and sample code below.

Lucene works on Documents that you fill with data that you get from
anywhere you like.  To index data in a database table you could use
something like:

	Analyzer analyzer = new StandardAnalyzer(); 
	IndexWriter writer = new IndexWriter("dbindex", analyzer, true);
	Connection conn = getConnection();
	String sql = "select id, firstname, lastname from people";
	Statement stmt = conn.createStatement(sql);
	ResultSet rs = stmt.executeQuery();
	while ( {
	    Document d = new Document();
	    d.add(Field.Text("id", rs.getString("id")));
	    d.add(Field.UnStored("firstname", rs.getString("firstname")));
	    d.add(Field.UnStored("lastname", rs.getString("lastname")));

The id field is indexed and stored since will want to extract it from lucene.
The name fields are not stored since they are already stored on the database,
although you could store them if wanted to avoid having to go back to the
database for display.

To search and display results, with details coming from the database,
something along the lines of:

	Searcher searcher = new IndexSearcher("dbindex"));
	Query query = QueryParser.parse("duncan", "firstname", analyzer);
	Hits hits =;
	String sql = "select * from people where id = ?";
	PreparedStatement pstmt = conn.prepareStatement(sql);
	for (int i = 0; i < hits.length(); i++) {
	    String id = hits.doc(i).get("id");
	    pstmt.setString(1, id);

Hope this helps.


To unsubscribe, e-mail:   <>
For additional commands, e-mail: <>

View raw message