Guest User

Untitled

a guest
Sep 10th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. Index a MySQL database with Apache Lucene, and keep them synchronized
  2. public static void main(String[] args) throws Exception {
  3.  
  4. Class.forName("com.mysql.jdbc.Driver").newInstance();
  5. Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/mydb", "root", "");
  6. StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
  7. IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_36, analyzer);
  8. IndexWriter writer = new IndexWriter(FSDirectory.open(INDEX_DIR), config);
  9.  
  10. String query = "SELECT id, name FROM tag";
  11. Statement statement = connection.createStatement();
  12. ResultSet result = statement.executeQuery(query);
  13.  
  14. while (result.next()) {
  15. Document document = new Document();
  16. document.add(new Field("id", result.getString("id"), Field.Store.YES, Field.Index.NOT_ANALYZED));
  17. document.add(new Field("name", result.getString("name"), Field.Store.NO, Field.Index.ANALYZED));
  18. writer.updateDocument(new Term("id", result.getString("id")), document);
  19. }
  20.  
  21. writer.close();
  22.  
  23. }
  24.  
  25. writer.deleteAll();
  26. while (result.next()) {
  27. Document document = new Document();
  28. document.add(new Field("id", result.getString("id"), Field.Store.YES, Field.Index.NOT_ANALYZED));
  29. document.add(new Field("name", result.getString("name"), Field.Store.NO, Field.Index.ANALYZED));
  30. writer.addDocument(document);
  31. }
Add Comment
Please, Sign In to add comment