Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add filtered queries. #64

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions corpus_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,25 @@ def transform(text):
except ValueError:
continue

if doc["url"] == "":
url = doc["url"]
if url == "":
continue

filters = []
id_hash = hash(doc["url"])

if id_hash % 2 == 0:
filters.append("50%")
if id_hash % 10 == 3:
filters.append("10%")
if id_hash % 100 == 42:
filters.append("1%")

doc_transformed = {
"id": doc["url"],
"id": url,
"text": transform(doc["body"])
}
if len(filters) > 0:
doc_transformed["filter"] = filters

print(json.dumps(doc_transformed))
31 changes: 21 additions & 10 deletions engines/lucene-10.0.0-bp/src/main/java/BuildIndex.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
Expand All @@ -26,7 +27,9 @@
import org.apache.lucene.util.ThreadInterruptedException;

import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;

public class BuildIndex {

Expand All @@ -37,11 +40,11 @@ public static void main(String[] args) throws Exception {
final IndexWriterConfig config = new IndexWriterConfig(standardAnalyzer)
.setRAMBufferSizeMB(1024)
.setOpenMode(OpenMode.CREATE);
final BPIndexReorderer reorderer = new BPIndexReorderer();
reorderer.setRAMBudgetMB(256);
final BPReorderingMergePolicy mp = new BPReorderingMergePolicy(config.getMergePolicy(), reorderer);
mp.setMinNaturalMergeNumDocs(Integer.MAX_VALUE); // only reorder at force-merge time
config.setMergePolicy(mp);
final BPIndexReorderer reorderer = new BPIndexReorderer();
reorderer.setRAMBudgetMB(256);
final BPReorderingMergePolicy mp = new BPReorderingMergePolicy(config.getMergePolicy(), reorderer);
mp.setMinNaturalMergeNumDocs(Integer.MAX_VALUE); // only reorder at force-merge time
config.setMergePolicy(mp);

try (Directory dir = FSDirectory.open(outputPath);
IndexWriter writer = new IndexWriter(dir, config);
Expand All @@ -53,13 +56,9 @@ public static void main(String[] args) throws Exception {
final AtomicInteger indexed = new AtomicInteger();
for (int i = 0; i < threads.length; ++i) {

final Document document = new Document();
StoredField idField = new StoredField("id", "");
TextField textField = new TextField("text", "", Field.Store.NO);

document.add(idField);
document.add(textField);

threads[i] = new Thread(() -> {
while (true) {
String line;
Expand All @@ -83,13 +82,25 @@ public static void main(String[] args) throws Exception {
final JsonObject parsed_doc = Json.parse(line).asObject();
final String id = parsed_doc.get("id").asString();
final String text = parsed_doc.get("text").asString();
final JsonValue filter = parsed_doc.get("filter");
idField.setStringValue(id);
textField.setStringValue(text);

Document document = new Document();
document.add(idField);
document.add(textField);
if (filter != null) {
JsonArray filterArray = filter.asArray();
for (int j = 0; j < filterArray.size(); ++j) {
document.add(new StringField("filter", filterArray.get(j).asString(), Field.Store.NO));
}
}

try {
writer.addDocument(document);
final int numIndexed = indexed.getAndIncrement();
if (numIndexed % 100_000 == 0) {
System.out.println("Indexed: " + numIndexed);
System.out.println("Indexed: " + numIndexed);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
Expand Down
147 changes: 84 additions & 63 deletions engines/lucene-10.0.0-bp/src/main/java/DoQuery.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,79 +5,100 @@
import java.nio.file.Paths;

import org.apache.lucene.analysis.CharArraySet;
import org.apache.lucene.analysis.core.KeywordAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopScoreDocCollectorManager;
import org.apache.lucene.search.similarities.BM25Similarity;
import org.apache.lucene.store.FSDirectory;

public class DoQuery {
public static void main(String[] args) throws IOException, ParseException {
final Path indexDir = Paths.get(args[0]);
try (IndexReader reader = DirectoryReader.open(FSDirectory.open(indexDir));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
final IndexSearcher searcher = new IndexSearcher(reader);
searcher.setQueryCache(null);
searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f));
final QueryParser queryParser = new QueryParser("text", new StandardAnalyzer(CharArraySet.EMPTY_SET));
String line;
while ((line = bufferedReader.readLine()) != null) {
final String[] fields = line.trim().split("\t");
assert fields.length == 2;
final String command = fields[0];
final String query_str = fields[1];
Query query = queryParser.parse(query_str);
final long count;
switch (command) {
case "COUNT":
case "UNOPTIMIZED_COUNT":
count = searcher.count(query);
break;
case "TOP_10":
{
searcher.search(query, new TopScoreDocCollectorManager(10, null, 10, false));
count = 1;
}
break;
case "TOP_100":
{
searcher.search(query, new TopScoreDocCollectorManager(100, null, 100, false));
count = 1;
}
break;
case "TOP_1000":
{
searcher.search(query, new TopScoreDocCollectorManager(1000, null, 1000, false));
count = 1;
}
break;
case "TOP_10_COUNT":
{
count = searcher.search(query, new TopScoreDocCollectorManager(10, null, Integer.MAX_VALUE, false)).totalHits.value();
}
break;
case "TOP_100_COUNT":
{
count = searcher.search(query, new TopScoreDocCollectorManager(100, null, Integer.MAX_VALUE, false)).totalHits.value();
}
break;
case "TOP_1000_COUNT":
{
count = searcher.search(query, new TopScoreDocCollectorManager(1000, null, Integer.MAX_VALUE, false)).totalHits.value();
}
break;
default:
System.out.println("UNSUPPORTED");
count = 0;
break;
}
System.out.println(count);
}
}
}

private static final String FILTER_SEPARATOR = " WHERE ";

public static void main(String[] args) throws IOException, ParseException {
final Path indexDir = Paths.get(args[0]);
try (IndexReader reader = DirectoryReader.open(FSDirectory.open(indexDir));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
final IndexSearcher searcher = new IndexSearcher(reader);
searcher.setQueryCache(null);
searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f));
final QueryParser queryParser = new QueryParser("text", new StandardAnalyzer(CharArraySet.EMPTY_SET));
final QueryParser filterParser = new QueryParser("text", new KeywordAnalyzer());
String line;
while ((line = bufferedReader.readLine()) != null) {
final String[] fields = line.trim().split("\t");
assert fields.length == 2;
final String command = fields[0];
String query_str = fields[1];

int filterIdx = query_str.indexOf(FILTER_SEPARATOR);
Query filter = null;
if (filterIdx >= 0) {
String filter_str = query_str.substring(filterIdx + FILTER_SEPARATOR.length());
query_str = query_str.substring(0, filterIdx);
filter = filterParser.parse(filter_str);
}

Query query = queryParser.parse(query_str);
if (filter != null) {
query = new BooleanQuery.Builder().add(query, Occur.MUST).add(filter, Occur.FILTER).build();
}

final long count;
switch (command) {
case "COUNT":
case "UNOPTIMIZED_COUNT":
count = searcher.count(query);
break;
case "TOP_10":
{
TopDocs topDocs = searcher.search(query, new TopScoreDocCollectorManager(10, null, 10, false));
count = Math.min(topDocs.totalHits.value(), 10);
}
break;
case "TOP_100":
{
TopDocs topDocs = searcher.search(query, new TopScoreDocCollectorManager(100, null, 100, false));
count = Math.min(topDocs.totalHits.value(), 100);
}
break;
case "TOP_1000":
{
TopDocs topDocs = searcher.search(query, new TopScoreDocCollectorManager(1000, null, 1000, false));
count = Math.min(topDocs.totalHits.value(), 1000);
}
break;
case "TOP_10_COUNT":
{
count = searcher.search(query, new TopScoreDocCollectorManager(10, null, Integer.MAX_VALUE, false)).totalHits.value();
}
break;
case "TOP_100_COUNT":
{
count = searcher.search(query, new TopScoreDocCollectorManager(100, null, Integer.MAX_VALUE, false)).totalHits.value();
}
break;
case "TOP_1000_COUNT":
{
count = searcher.search(query, new TopScoreDocCollectorManager(1000, null, Integer.MAX_VALUE, false)).totalHits.value();
}
break;
default:
System.out.println("UNSUPPORTED");
count = 0;
break;
}
System.out.println(count);
}
}
}
}
21 changes: 16 additions & 5 deletions engines/lucene-10.0.0/src/main/java/BuildIndex.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
Expand All @@ -24,7 +25,9 @@
import org.apache.lucene.util.ThreadInterruptedException;

import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;

public class BuildIndex {

Expand All @@ -46,13 +49,9 @@ public static void main(String[] args) throws Exception {
final AtomicInteger indexed = new AtomicInteger();
for (int i = 0; i < threads.length; ++i) {

final Document document = new Document();
StoredField idField = new StoredField("id", "");
TextField textField = new TextField("text", "", Field.Store.NO);

document.add(idField);
document.add(textField);

threads[i] = new Thread(() -> {
while (true) {
String line;
Expand All @@ -76,13 +75,25 @@ public static void main(String[] args) throws Exception {
final JsonObject parsed_doc = Json.parse(line).asObject();
final String id = parsed_doc.get("id").asString();
final String text = parsed_doc.get("text").asString();
final JsonValue filter = parsed_doc.get("filter");
idField.setStringValue(id);
textField.setStringValue(text);

Document document = new Document();
document.add(idField);
document.add(textField);
if (filter != null) {
JsonArray filterArray = filter.asArray();
for (int j = 0; j < filterArray.size(); ++j) {
document.add(new StringField("filter", filterArray.get(j).asString(), Field.Store.NO));
}
}

try {
writer.addDocument(document);
final int numIndexed = indexed.getAndIncrement();
if (numIndexed % 100_000 == 0) {
System.out.println("Indexed: " + numIndexed);
System.out.println("Indexed: " + numIndexed);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
Expand Down
Loading