Add support for searching for a recipeId
This patch adds a new LondPoint to the index to allow us to query based on the recipeId. This is useful for using functionality that requires the (out of my control) document Id that lucene generates.
- Id
- 012d2590f4482af60976bcc999a09520a1bf6874
- Author
- Caio
- Commit time
- 2019-04-05T11:35:47+02:00
Modified src/main/java/co/caio/cerberus/search/Indexer.java
var doc = new Document();
doc.add(new StoredField(RECIPE_ID, recipe.recipeId()));
+ doc.add(new LongPoint(RECIPE_ID, recipe.recipeId()));
doc.add(new TextField(NAME, recipe.name(), Store.NO));
recipe.instructions().forEach(i -> doc.add(new TextField(INSTRUCTIONS, i, Store.NO)));
Modified src/main/java/co/caio/cerberus/search/SearcherImpl.java
import co.caio.cerberus.model.SearchResult;
import java.io.IOException;
import java.io.StringReader;
+import java.util.OptionalInt;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.FloatPoint;
import org.apache.lucene.document.IntPoint;
+import org.apache.lucene.document.LongPoint;
import org.apache.lucene.facet.FacetResult;
import org.apache.lucene.facet.FacetsCollector;
import org.apache.lucene.facet.taxonomy.FastTaxonomyFacetCounts;
} catch (IOException wrapped) {
throw new SearcherException(wrapped);
}
+ }
+
+ OptionalInt findDocId(long recipeId) throws IOException {
+ var result = indexSearcher.search(LongPoint.newExactQuery(RECIPE_ID, recipeId), 1);
+
+ if (result.scoreDocs.length == 0) {
+ return OptionalInt.empty();
+ }
+
+ return OptionalInt.of(result.scoreDocs[0].doc);
}
public int numDocs() {
Created src/test/java/co/caio/cerberus/search/SearcherImplTest.java
+package co.caio.cerberus.search;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import co.caio.cerberus.Util;
+import java.io.IOException;
+import org.junit.jupiter.api.Test;
+
+class SearcherImplTest {
+
+ @Test
+ void canFindEveryIndexedRecipe() {
+ var searcher = (SearcherImpl) Util.getTestIndexer().buildSearcher();
+
+ Util.getSampleRecipes()
+ .forEach(
+ sampleRecipe -> {
+ try {
+ var maybeDocId = searcher.findDocId(sampleRecipe.recipeId());
+ assertTrue(maybeDocId.isPresent());
+ } catch (IOException wrapped) {
+ throw new RuntimeException(wrapped);
+ }
+ });
+ }
+}