use of org.h2.tools.SimpleResultSet in project siena by mandubian.
the class FullText method search.
/**
* Do the search.
*
* @param conn the database connection
* @param text the query
* @param limit the limit
* @param offset the offset
* @param data whether the raw data should be returned
* @return the result set
*/
protected static ResultSet search(Connection conn, String text, int limit, int offset, boolean data) throws SQLException {
SimpleResultSet result = createResultSet(data);
if (conn.getMetaData().getURL().startsWith("jdbc:columnlist:")) {
// this is just to query the result set columns
return result;
}
if (text == null || text.trim().length() == 0) {
return result;
}
FullTextSettings setting = FullTextSettings.getInstance(conn);
if (!setting.isInitialized()) {
init(conn);
}
HashSet<String> words = New.hashSet();
addWords(setting, words, text);
HashSet<Integer> rIds = null, lastRowIds = null;
HashMap<String, Integer> allWords = setting.getWordList();
PreparedStatement prepSelectMapByWordId = setting.prepare(conn, SELECT_MAP_BY_WORD_ID);
for (String word : words) {
lastRowIds = rIds;
rIds = New.hashSet();
Integer wId = allWords.get(word);
if (wId == null) {
continue;
}
prepSelectMapByWordId.setInt(1, wId.intValue());
ResultSet rs = prepSelectMapByWordId.executeQuery();
while (rs.next()) {
Integer rId = rs.getInt(1);
if (lastRowIds == null || lastRowIds.contains(rId)) {
rIds.add(rId);
}
}
}
if (rIds == null || rIds.size() == 0) {
return result;
}
PreparedStatement prepSelectRowById = setting.prepare(conn, SELECT_ROW_BY_ID);
int rowCount = 0;
for (int rowId : rIds) {
prepSelectRowById.setInt(1, rowId);
ResultSet rs = prepSelectRowById.executeQuery();
if (!rs.next()) {
continue;
}
if (offset > 0) {
offset--;
} else {
String key = rs.getString(1);
int indexId = rs.getInt(2);
IndexInfo index = setting.getIndexInfo(indexId);
if (data) {
/*Object[][] columnData = parseKey(conn, key);
result.addRow(
index.schema,
index.table,
columnData[0],
columnData[1],
1.0);*/
String[] splits = key.split("=");
String[] col0 = new String[1];
col0[0] = splits[0];
String[] col1 = new String[1];
col1[0] = splits[1];
result.addRow(index.schema, index.table, col0, col1, 1.0);
} else {
String query = StringUtils.quoteIdentifier(index.schema) + "." + StringUtils.quoteIdentifier(index.table) + " WHERE " + key;
result.addRow(query, 1.0);
}
rowCount++;
if (limit > 0 && rowCount >= limit) {
break;
}
}
}
return result;
}
use of org.h2.tools.SimpleResultSet in project elastic-core-maven by OrdinaryDude.
the class FullTextTrigger method search.
/**
* Search the Lucene index
*
* The result set will have the following columns:
* SCHEMA - Schema name (String)
* TABLE - Table name (String)
* COLUMNS - Primary key column names (String[]) - this is always DB_ID
* KEYS - Primary key values (Long[]) - this is always the DB_ID value for the table row
* SCORE - Lucene score (Float)
*
* @param conn SQL connection
* @param schema Schema name
* @param table Table name
* @param queryText Query expression
* @param limit Number of rows to return
* @param offset Offset with result set
* @return Search results
* @throws SQLException Unable to search the index
*/
public static ResultSet search(Connection conn, String schema, String table, String queryText, int limit, int offset) throws SQLException {
//
// Get Lucene index access
//
getIndexAccess(conn);
//
// Create the result set columns
//
SimpleResultSet result = new SimpleResultSet();
result.addColumn("SCHEMA", Types.VARCHAR, 0, 0);
result.addColumn("TABLE", Types.VARCHAR, 0, 0);
result.addColumn("COLUMNS", Types.ARRAY, 0, 0);
result.addColumn("KEYS", Types.ARRAY, 0, 0);
result.addColumn("SCORE", Types.FLOAT, 0, 0);
//
// Perform the search
//
// The _QUERY field contains the table and row identification (schema.table;keyName;keyValue)
// The _TABLE field is used to limit the search results to the current table
// The _DATA field contains the indexed row data (this is the default search field)
// The _MODIFIED field contains the row modification time (YYYYMMDDhhmmss) in GMT
//
indexLock.readLock().lock();
try {
QueryParser parser = new QueryParser("_DATA", analyzer);
parser.setDateResolution("_MODIFIED", DateTools.Resolution.SECOND);
parser.setDefaultOperator(QueryParser.Operator.AND);
Query query = parser.parse("_TABLE:" + schema.toUpperCase() + "." + table.toUpperCase() + " AND (" + queryText + ")");
TopDocs documents = indexSearcher.search(query, limit);
ScoreDoc[] hits = documents.scoreDocs;
int resultCount = Math.min(hits.length, (limit == 0 ? hits.length : limit));
int resultOffset = Math.min(offset, resultCount);
for (int i = resultOffset; i < resultCount; i++) {
Document document = indexSearcher.doc(hits[i].doc);
String[] indexParts = document.get("_QUERY").split(";");
String[] nameParts = indexParts[0].split("\\.");
result.addRow(nameParts[0], nameParts[1], new String[] { indexParts[1] }, new Long[] { Long.parseLong(indexParts[2]) }, hits[i].score);
}
} catch (ParseException exc) {
Logger.logDebugMessage("Lucene parse exception for query: " + queryText + "\n" + exc.getMessage());
throw new SQLException("Lucene parse exception for query: " + queryText + "\n" + exc.getMessage());
} catch (IOException exc) {
Logger.logErrorMessage("Unable to search Lucene index", exc);
throw new SQLException("Unable to search Lucene index", exc);
} finally {
indexLock.readLock().unlock();
}
return result;
}
use of org.h2.tools.SimpleResultSet in project frostwire by frostwire.
the class FullTextLucene2 method search.
/**
* Do the search.
*
* @param conn the database connection
* @param text the query
* @param limit the limit
* @param offset the offset
* @param data whether the raw data should be returned
* @return the result set
*/
protected static ResultSet search(Connection conn, String text, int limit, int offset, boolean data) throws SQLException {
SimpleResultSet result = createResultSet(data);
if (conn.getMetaData().getURL().startsWith("jdbc:columnlist:")) {
// this is just to query the result set columns
return result;
}
if (text == null || text.trim().length() == 0) {
return result;
}
try {
IndexAccess access = getIndexAccess(conn);
/*## LUCENE2 ##
access.modifier.flush();
String path = getIndexPath(conn);
IndexReader reader = IndexReader.open(path);
Analyzer analyzer = new StandardAnalyzer();
Searcher searcher = new IndexSearcher(reader);
QueryParser parser = new QueryParser(LUCENE_FIELD_DATA, analyzer);
Query query = parser.parse(text);
Hits hits = searcher.search(query);
int max = hits.length();
if (limit == 0) {
limit = max;
}
for (int i = 0; i < limit && i + offset < max; i++) {
Document doc = hits.doc(i + offset);
float score = hits.score(i + offset);
//*/
// ## LUCENE3 ##
// take a reference as the searcher may change
Searcher searcher = access.searcher;
// reuse the same analyzer; it's thread-safe;
// also allows subclasses to control the analyzer used.
Analyzer analyzer = access.writer.getAnalyzer();
QueryParser parser = new QueryParser(Version.LUCENE_30, LUCENE_FIELD_DATA, analyzer);
Query query = parser.parse(text);
// Lucene 3 insists on a hard limit and will not provide
// a total hits value. Take at least 100 which is
// an optimal limit for Lucene as any more
// will trigger writing results to disk.
int maxResults = (limit == 0 ? 100 : limit) + offset;
TopDocs docs = searcher.search(query, maxResults);
if (limit == 0) {
limit = docs.totalHits;
}
for (int i = 0, len = docs.scoreDocs.length; i < limit && i + offset < docs.totalHits && i + offset < len; i++) {
ScoreDoc sd = docs.scoreDocs[i + offset];
Document doc = searcher.doc(sd.doc);
float score = sd.score;
// */
String q = doc.get(LUCENE_FIELD_QUERY);
if (data) {
int idx = q.indexOf(" WHERE ");
JdbcConnection c = (JdbcConnection) conn;
Session session = (Session) c.getSession();
Parser p = new Parser(session);
String tab = q.substring(0, idx);
ExpressionColumn expr = (ExpressionColumn) p.parseExpression(tab);
String schemaName = expr.getOriginalTableAliasName();
String tableName = expr.getColumnName();
q = q.substring(idx + " WHERE ".length());
Object[][] columnData = parseKey(conn, q);
result.addRow(schemaName, tableName, columnData[0], columnData[1], score);
} else {
result.addRow(q, score);
}
}
/*## LUCENE2 ##
// TODO keep it open if possible
reader.close();
//*/
} catch (Exception e) {
throw convertException(e);
}
return result;
}
use of org.h2.tools.SimpleResultSet in project microservices by pwillhan.
the class Procedures method simple.
public static ResultSet simple() throws SQLException {
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("ID", Types.INTEGER, 10, 0);
rs.addColumn("NAME", Types.VARCHAR, 255, 0);
rs.addRow(0, "Hello");
rs.addRow(1, "World");
return rs;
}
use of org.h2.tools.SimpleResultSet in project h2database by h2database.
the class WebApp method addDatabaseMetaData.
private static void addDatabaseMetaData(SimpleResultSet rs, DatabaseMetaData meta) {
Method[] methods = DatabaseMetaData.class.getDeclaredMethods();
Arrays.sort(methods, new Comparator<Method>() {
@Override
public int compare(Method o1, Method o2) {
return o1.toString().compareTo(o2.toString());
}
});
for (Method m : methods) {
if (m.getParameterTypes().length == 0) {
try {
Object o = m.invoke(meta);
rs.addRow("meta." + m.getName(), "" + o);
} catch (InvocationTargetException e) {
rs.addRow("meta." + m.getName(), e.getTargetException().toString());
} catch (Exception e) {
rs.addRow("meta." + m.getName(), e.toString());
}
}
}
}
Aggregations