· 7 years ago · Oct 04, 2018, 04:30 PM
1package com.github.kilianB;
2
3import java.sql.Connection;
4import java.sql.DriverManager;
5import java.sql.ResultSet;
6import java.sql.SQLException;
7import java.sql.Statement;
8
9/**
10 * @author Kilian
11 *
12 */
13public class LuceneEscapedSearch {
14
15 private static Connection conn;
16
17 public static void setup() throws SQLException {
18
19 conn = DriverManager.getConnection("jdbc:h2:~/luceneExample", "sa", "");
20
21 try (Statement stmt = conn.createStatement()) {
22
23 //Reset databse
24 stmt.execute("DROP ALL OBJECTS");
25
26 // Create table
27 stmt.execute("CREATE TABLE t(path VARCHAR(100), PRIMARY KEY(path) )");
28
29 // Insert dummy entries
30 stmt.executeUpdate("INSERT INTO t VALUES('C:\\HelloWorld\\RandomPath1.txt')");
31 stmt.executeUpdate("INSERT INTO t VALUES('C:\\HelloWorld\\RandomPath2.txt')");
32 stmt.executeUpdate("INSERT INTO t VALUES('C:\\HelloWorld\\RandomPath3.txt')");
33
34 // Initialize full text search
35 stmt.execute("CREATE ALIAS IF NOT EXISTS FTL_INIT FOR \"org.h2.fulltext.FullTextLucene.init\";");
36 stmt.execute("CALL FTL_INIT();");
37 stmt.execute("CALL FTL_CREATE_INDEX('PUBLIC', 'T', 'PATH');");
38 stmt.execute("CALL FTL_REINDEX();"); // Just to be sure
39 }
40
41 }
42
43 private static boolean searchWithoutDelimiter() throws SQLException {
44
45 try (Statement stmt = conn.createStatement()) {
46
47 ResultSet rs = conn.createStatement().executeQuery("SELECT COUNT(*) FROM FTL_SEARCH('C*',0,0);");
48 if (rs.next()) {
49 return rs.getInt(1) == 3;
50 }
51 }
52 return false;
53 }
54
55 private static boolean searchWithDelimiter() throws SQLException {
56
57 try (Statement stmt = conn.createStatement()) {
58
59 ResultSet rs = conn.createStatement().executeQuery("SELECT COUNT(*) FROM FTL_SEARCH('C\\:*',0,0);");
60 if (rs.next()) {
61 return rs.getInt(1) == 3;
62 }
63 }
64 return false;
65 }
66
67 public static void main(String[] args) throws SQLException{
68 try {
69 setup();
70 System.out.printf("%-7s : %b %n","Without",searchWithoutDelimiter());
71 System.out.printf("%-7s : %b %n","With",searchWithDelimiter());
72 } catch (SQLException e) {
73 e.printStackTrace();
74 }finally {
75 //teardown
76 conn.close();
77 }
78 }
79
80 private static String escapeLuceneQuery(String input) {
81 // +\\-:!(){}[\\]^\"~*?:
82 input = input.replace("\\", "\\\\");
83 input = input.replaceAll("([+\\-:!(){}\\[\\]^\"~*?]|(&&))", "\\\\$1");
84 input = input.replace("||", "\\||");
85 return input;
86 }
87
88 /*
89 <dependency>
90 <groupId>com.h2database</groupId>
91 <artifactId>h2</artifactId>
92 <version>1.4.197</version>
93 </dependency>
94
95 <dependency>
96 <groupId>org.apache.lucene</groupId>
97 <artifactId>lucene-core</artifactId>
98 <version>3.6.2</version>
99 </dependency>
100 */
101}