lucene-java-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Ian Lea <ian....@blackwell.co.uk>
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 http://www.darksleep.com/puff/lucene/lucene.html
 
> 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 (rs.next()) {
	    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")));
	    writer.addDocument(d);
	}
	writer.close();

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(IndexReader.open("dbindex"));
	Query query = QueryParser.parse("duncan", "firstname", analyzer);
	Hits hits = searcher.search(query);
	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);
	    displayResults(pstmt);
	}



Hope this helps.



--
Ian.
ian.lea@blackwell.co.uk

--
To unsubscribe, e-mail:   <mailto:lucene-user-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:lucene-user-help@jakarta.apache.org>


Mime
View raw message