1 /*******************************************************************************
2 * Copyright (c) 2007, 2015 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 * Semantum Oy - Fix for simantics issue #6053
12 *******************************************************************************/
13 package org.simantics.db.indexing;
15 import java.io.IOException;
16 import java.nio.file.Files;
17 import java.nio.file.Path;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.Iterator;
22 import java.util.List;
24 import java.util.concurrent.CompletableFuture;
25 import java.util.concurrent.Semaphore;
26 import java.util.concurrent.atomic.AtomicReference;
28 import org.apache.lucene.document.Document;
29 import org.apache.lucene.document.DocumentStoredFieldVisitor;
30 import org.apache.lucene.document.Field;
31 import org.apache.lucene.document.FieldType;
32 import org.apache.lucene.document.LongField;
33 import org.apache.lucene.document.TextField;
34 import org.apache.lucene.index.CorruptIndexException;
35 import org.apache.lucene.index.DirectoryReader;
36 import org.apache.lucene.index.FieldInfo;
37 import org.apache.lucene.index.IndexNotFoundException;
38 import org.apache.lucene.index.IndexReader;
39 import org.apache.lucene.index.IndexWriter;
40 import org.apache.lucene.index.IndexWriterConfig;
41 import org.apache.lucene.index.IndexWriterConfig.OpenMode;
42 import org.apache.lucene.index.IndexableField;
43 import org.apache.lucene.index.StoredFieldVisitor;
44 import org.apache.lucene.index.Term;
45 import org.apache.lucene.queryparser.classic.ParseException;
46 import org.apache.lucene.search.IndexSearcher;
47 import org.apache.lucene.search.MatchAllDocsQuery;
48 import org.apache.lucene.search.Query;
49 import org.apache.lucene.search.ScoreDoc;
50 import org.apache.lucene.search.TermQuery;
51 import org.apache.lucene.search.TopDocs;
52 import org.apache.lucene.store.Directory;
53 import org.apache.lucene.store.FSDirectory;
54 import org.apache.lucene.util.Version;
55 import org.eclipse.core.runtime.IProgressMonitor;
56 import org.eclipse.core.runtime.SubMonitor;
57 import org.simantics.databoard.util.ObjectUtils;
58 import org.simantics.db.ReadGraph;
59 import org.simantics.db.RequestProcessor;
60 import org.simantics.db.Resource;
61 import org.simantics.db.Session;
62 import org.simantics.db.common.request.SafeName;
63 import org.simantics.db.common.utils.NameUtils;
64 import org.simantics.db.exception.DatabaseException;
65 import org.simantics.db.indexing.exception.IndexCorruptedException;
66 import org.simantics.db.indexing.exception.IndexingException;
67 import org.simantics.db.indexing.internal.IndexingJob;
68 import org.simantics.db.layer0.adapter.GenericRelation;
69 import org.simantics.db.layer0.genericrelation.IndexException;
70 import org.simantics.db.request.Read;
71 import org.simantics.db.service.CollectionSupport;
72 import org.simantics.db.service.SerialisationSupport;
73 import org.simantics.utils.FileUtils;
74 import org.simantics.utils.datastructures.Pair;
75 import org.simantics.utils.threads.ThreadUtils;
76 import org.slf4j.Logger;
78 import gnu.trove.map.hash.THashMap;
81 * @author Tuukka Lehtonen
82 * @author Antti Villberg
84 abstract public class IndexedRelationsSearcherBase {
86 protected enum State {
87 // No index is available
89 // An index is available, but there is a problem with it
91 // An index is available but no reader or writer is ready
95 // A writer (and a reader) is ready
99 private State state = State.READY;
100 private Throwable exception;
102 public Throwable getException() {
106 public void setProblem(Throwable t) {
108 getLogger().error("Setting problem for {} and previous state {}", this, this.state, t);
109 this.state = State.PROBLEM;
113 public void setNone() {
114 this.state = State.NONE;
117 public void setReady() {
118 this.state = State.READY;
121 public State state() {
125 protected boolean checkState(State state) {
126 return this.state == state;
129 protected void assertState(State state) throws IndexException {
130 State s = this.state;
132 throw new IndexException("Illegal index searcher state, expected " + state.name() + " but state was " + s.name());
135 public void changeState(IProgressMonitor monitor, Session session, State state) {
136 changeState(monitor, session, state, 0);
139 protected void changeState(IProgressMonitor monitor, Session session, State state, int depth) {
141 if (this.state == state) {
142 if (getLogger().isDebugEnabled())
143 getLogger().debug("Trying to change state {} to the same as previous state {} in depth {} with {}", state, this.state, depth, this);
147 if (IndexPolicy.TRACE_INDEX_MANAGEMENT)
148 System.err.println("Index state " + this.state.name() + " => " + state.name() + " " + this);
152 // Try to exit problem state
153 if (State.PROBLEM == this.state && depth > 0) {
154 getLogger().info("Try to exit problem state for {} and state {}", this, state);
155 Throwable t = bestEffortClear(monitor, session);
157 getLogger().error("Best effort clear has failed for state {} and this {}", state, this, t);
161 // Managed to get into initial state
162 this.state = State.NONE;
163 getLogger().info("Managed to get into initial state {}", this.state);
167 // Cannot move into read from no index
168 if (State.NONE == this.state && State.READ == state) {
169 if (getLogger().isDebugEnabled())
170 getLogger().debug("Cannot move into read from no index in {} with state {}", this, state);
173 // Cannot move into write from no index
174 if (State.NONE == this.state && State.WRITE == state) {
175 if (getLogger().isDebugEnabled())
176 getLogger().debug("Cannot move into write from no index in {} with state {}", this, state);
180 boolean success = false;
184 if (searcher != null) {
187 if (reader != null) {
197 if (State.READ == state || State.WRITE == state) {
201 boolean forWriting = State.WRITE == state;
203 if (directory != null)
204 throw new IllegalStateException(getDescriptor() + "Index already loaded");
206 SubMonitor mon = SubMonitor.convert(monitor, 100);
208 mon.beginTask("Loading index", 100);
210 if (IndexPolicy.TRACE_INDEX_LOAD)
211 System.out.println(getDescriptor() + "Loading Lucene index from " + indexPath + " for " + (forWriting ? "writing" : "reading"));
213 long start = System.nanoTime();
215 directory = getDirectory(session);
218 // Never overwrite an index that is about to be loaded.
219 // TODO: could use OpenMode.CREATE_OR_APPEND but must test first
220 IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_9, Queries.getAnalyzer()).setOpenMode(OpenMode.APPEND);
222 // FIXME: platform #4676
223 writer = new IndexWriter(directory, config);
224 } catch (IndexNotFoundException e) {
225 // There was no pre-existing index on disk. Create it now.
226 writer = new IndexWriter(directory, config.setOpenMode(OpenMode.CREATE));
229 reader = DirectoryReader.open(directory);
230 searcher = new IndexSearcher(reader);
232 reader = DirectoryReader.open(directory);
233 searcher = new IndexSearcher(reader);
236 long end = System.nanoTime();
240 if (IndexPolicy.PERF_INDEX_LOAD) {
241 double time = (end - start) * 1e-6;
242 System.out.println(getDescriptor() + "Loaded Lucene index from " + indexPath + " for " + (forWriting ? "writing" : "reading") + " in " + time + " ms");
249 } catch (Throwable t) {
254 this.state = State.PROBLEM;
255 changeState(monitor, session, State.NONE, depth+1);
265 public static final FieldType STRING_TYPE = new FieldType();
268 STRING_TYPE.setIndexed(true);
269 STRING_TYPE.setStored(true);
270 STRING_TYPE.setTokenized(true);
271 STRING_TYPE.freeze();
274 protected static Field makeField(String fieldName, String fieldClass) throws IndexingException {
275 switch (fieldClass) {
276 case "Long": return new LongField(fieldName, 0L, Field.Store.YES);
277 case "String": return new Field (fieldName, "", STRING_TYPE);
278 case "Text": return new TextField(fieldName, "", Field.Store.YES);
280 throw new IndexingException("Can only index Long, String and Text fields, encountered field type " + fieldClass);
284 protected static Field[] makeFieldsForRelation(GenericRelation r, int boundLength, Document document) throws DatabaseException {
285 Pair<String, String>[] fields = r.getFields();
286 Field[] fs = new Field[Math.max(0, fields.length - boundLength)];
287 for (int i = boundLength; i < fields.length; i++) {
288 Field f = makeField(fields[i].first, fields[i].second);
289 fs[i - boundLength] = f;
290 if (document != null)
296 void insertIndex(IProgressMonitor monitor, GenericRelation r, int boundLength, Collection<Object[]> documentsData)
297 throws CorruptIndexException, IOException, DatabaseException {
298 assertAccessOpen(true);
300 if (IndexPolicy.TRACE_INDEX_UPDATE)
301 System.out.println(getDescriptor() + "Inserting " + documentsData.size() + " documents into index at " + indexPath);
303 long start = 0, end = 0;
304 if (IndexPolicy.PERF_INDEX_UPDATE)
305 start = System.nanoTime();
308 Document document = new Document();
309 Field[] fs = makeFieldsForRelation(r, boundLength, document);
311 for (Object[] documentData : documentsData) {
312 if (setFields(fs, documentData) == null)
315 if (IndexPolicy.TRACE_INDEX_UPDATE)
316 System.out.println(getDescriptor() + "Inserting document " + document);
318 writer.addDocument(document);
321 if (IndexPolicy.PERF_INDEX_UPDATE) {
322 end = System.nanoTime();
323 double ms = (end - start) * 1e-6;
324 System.out.println(getDescriptor() + "Inserted " + documentsData.size() + " documents into index at " + indexPath + " in " + ms + " ms");
331 void removeIndex(IProgressMonitor monitor, GenericRelation r, RequestProcessor processor, String key, Collection<Object> keyValues) throws DatabaseException, CorruptIndexException, IOException {
332 assertAccessOpen(true);
334 if (IndexPolicy.TRACE_INDEX_UPDATE)
335 System.out.println(getDescriptor() + "Removing " + keyValues.size() + " documents from index at " + indexPath);
337 long start = 0, end = 0;
338 if (IndexPolicy.PERF_INDEX_UPDATE)
339 start = System.nanoTime();
342 for (Object keyValue : keyValues) {
343 Term removedTerm = null;
344 if (keyValue instanceof Long) {
345 removedTerm = IndexUtils.longTerm(key, (Long) keyValue);
346 } else if (keyValue instanceof String) {
347 removedTerm = new Term(key, (String) keyValue);
349 // FIXME: should throw an exception for illegal input data but this would leave the index in an incoherent state
353 if (IndexPolicy.TRACE_INDEX_UPDATE)
354 System.out.println(getDescriptor() + "Removing document with key " + removedTerm);
355 writer.deleteDocuments(removedTerm);
358 if (IndexPolicy.PERF_INDEX_UPDATE) {
359 end = System.nanoTime();
360 double ms = (end - start) * 1e-6;
361 System.out.println(getDescriptor() + "Removed " + keyValues.size() + " documents from index at " + indexPath + " in " + ms + " ms");
368 void removeIndex(IProgressMonitor monitor) throws DatabaseException, CorruptIndexException, IOException {
369 assertAccessOpen(true);
371 long start = 0, end = 0;
372 if (IndexPolicy.PERF_INDEX_UPDATE)
373 start = System.nanoTime();
379 if (IndexPolicy.PERF_INDEX_UPDATE) {
380 end = System.nanoTime();
381 double ms = (end - start) * 1e-6;
382 System.out.println(getDescriptor() + "Removed all documents from index at " + indexPath + " in " + ms + " ms");
389 boolean replaceIndex(IProgressMonitor monitor, String key, Collection<Object> keyValues, GenericRelation r, int boundLength, Collection<Object[]> documentsData) throws CorruptIndexException, IOException, DatabaseException {
391 boolean didReplace = false;
393 assertAccessOpen(true);
394 if (keyValues.size() != documentsData.size())
395 throw new IllegalArgumentException("keyValues size does not match documents data size, " + keyValues.size() + " <> " + documentsData.size());
397 if (IndexPolicy.TRACE_INDEX_UPDATE)
398 System.out.println(getDescriptor() + "Replacing " + keyValues.size() + " documents from index at " + indexPath);
400 long start = 0, end = 0;
401 if (IndexPolicy.PERF_INDEX_UPDATE)
402 start = System.nanoTime();
405 Iterator<Object> keyIt = keyValues.iterator();
406 Iterator<Object[]> documentDataIt = documentsData.iterator();
408 Document document = new Document();
409 Field[] fs = makeFieldsForRelation(r, boundLength, document);
412 while (keyIt.hasNext()) {
413 Object keyValue = keyIt.next();
414 Object[] documentData = documentDataIt.next();
416 Term removedTerm = null;
417 if (keyValue instanceof Long) {
418 removedTerm = IndexUtils.longTerm(key, (Long) keyValue);
419 } else if (keyValue instanceof String) {
420 removedTerm = new Term(key, (String) keyValue);
422 // FIXME: should throw an exception for illegal input data but this would leave the index in an incoherent state
423 System.err.println("[" + getClass().getSimpleName() + "] Unrecognized document key to remove '" + keyValue + "', only " + String.class + " and " + Resource.class + " are supported.");
424 continue nextDocument;
427 if (setFields(fs, documentData) == null)
428 continue nextDocument;
430 if (IndexPolicy.TRACE_INDEX_UPDATE)
431 System.out.println(getDescriptor() + "Replacing document with key " + removedTerm + " with " + document);
433 boolean done = false;
434 if(requireChangeInfoOnReplace()) {
435 TopDocs exist = searcher.search(new TermQuery(removedTerm), null, 2);
436 if(exist.scoreDocs.length == 1 && requireChangeInfoOnReplace()) {
437 Document doc = reader.document(exist.scoreDocs[0].doc);
438 if(!areSame(doc, document)) {
439 writer.deleteDocuments(removedTerm);
440 writer.addDocument(document);
442 if (IndexPolicy.TRACE_INDEX_UPDATE)
443 System.out.println("-replaced single existing");
445 if (IndexPolicy.TRACE_INDEX_UPDATE)
446 System.out.println("-was actually same than single existing");
452 writer.deleteDocuments(removedTerm);
453 writer.addDocument(document);
455 if (IndexPolicy.TRACE_INDEX_UPDATE)
456 System.out.println("-had many or none - removed all existing");
461 if (IndexPolicy.PERF_INDEX_UPDATE) {
462 end = System.nanoTime();
463 double ms = (end - start) * 1e-6;
464 System.out.println(getDescriptor() + "Replaced " + keyValues.size() + " documents from index at " + indexPath + " in " + ms + " ms");
474 protected boolean requireChangeInfoOnReplace() {
478 private boolean areSame(Document d1, Document d2) {
479 List<IndexableField> fs1 = d1.getFields();
480 List<IndexableField> fs2 = d2.getFields();
481 if(fs1.size() != fs2.size()) return false;
482 for(int i=0;i<fs1.size();i++) {
483 IndexableField f1 = fs1.get(i);
484 IndexableField f2 = fs2.get(i);
485 String s1 = f1.stringValue();
486 String s2 = f2.stringValue();
487 if (IndexPolicy.TRACE_INDEX_UPDATE)
488 System.err.println("areSame " + s1 + " vs. " + s2 );
489 if(!ObjectUtils.objectEquals(s1,s2)) return false;
494 final RequestProcessor session;
496 final Resource relation;
499 * The schema of the index, i.e. the fields that will be indexed per
500 * document for the specified relation. Since the relation stays the same
501 * throughout the lifetime of this class, the index schema is also assumed
502 * to the same. This means that {@link GenericRelation#getFields()} is
503 * assumed to stay the same.
505 final IndexSchema schema;
517 IndexSearcher searcher;
519 IndexedRelationsSearcherBase(RequestProcessor session, Resource relation, Resource input) {
520 this.session = session;
521 this.relation = relation;
523 this.indexPath = getIndexDirectory(session.getSession(), relation, input);
524 if(isIndexAvailable()) {
529 this.schema = IndexSchema.readFromRelation(session, relation);
532 Directory getDirectory(Session session) throws IOException {
533 return FSDirectory.open(indexPath.toFile());
536 abstract String getDescriptor();
539 * Ensures that searcher is in read or write state.
541 * @param forWriting <code>true</code> to open index for writing,
542 * <code>false</code> for reading
543 * @return true is required state was reached
546 boolean startAccess(IProgressMonitor monitor, Session session, boolean forWriting) {
548 changeState(monitor, session, State.WRITE);
549 return checkState(State.WRITE);
551 changeState(monitor, session, State.READ);
552 return checkState(State.READ);
556 boolean hasAccess(boolean forWriting) {
559 return checkState(State.WRITE);
561 return checkState(State.WRITE) || checkState(State.READ);
565 void assertAccessOpen(boolean forWriting) {
567 if(!checkState(State.WRITE))
568 throw new IllegalStateException("index not opened for writing (directory=" + directory + ", reader=" + reader + ")");
570 if(!(checkState(State.WRITE) || checkState(State.READ)))
571 throw new IllegalStateException("index not opened for reading (directory=" + directory + ", writer=" + writer + ")");
574 void closeWriter(IndexWriter writer) throws CorruptIndexException, IOException {
579 // May throw OOME, see IndexWriter javadoc for the correct actions.
581 } catch (OutOfMemoryError e) {
587 public static String getPattern(GenericRelation relation, int boundCount) {
589 for (int i = 0; i < boundCount; i++)
591 for (int i = 0; i < relation.getFields().length - boundCount; i++)
596 void initializeIndex(IProgressMonitor monitor, ReadGraph graph, Object[] bound, boolean overwrite)
597 throws IOException, DatabaseException
599 IndexingJob.jobifyIfPossible(
601 "Reindexing " + NameUtils.getSafeLabel(graph, input),
604 GenericRelation r = graph.adapt(relation, GenericRelation.class);
606 throw new IndexingException("Given resource " + relation + "could not be adapted to GenericRelation.");
608 GenericRelation selection = r.select(getPattern(r, bound.length), bound);
610 List<Object[]> results = selection.realize(graph);
611 initializeIndexImpl(new CompletableFuture<>(), mon, r, results, bound, overwrite);
612 } catch (IOException e) {
613 getLogger().error("Index is in problematic state! {}", this, e);
614 throw new IndexingException(e);
619 private static final int INDEXING_THREAD_COUNT = 2; // this is quite good parallelism level for lucene
621 void initializeIndexImpl(CompletableFuture<?> result, IProgressMonitor monitor, GenericRelation r, List<Object[]> results, final Object[] bound, boolean overwrite) throws IOException {
623 final SubMonitor mon = SubMonitor.convert(monitor, 100);
625 if (IndexPolicy.TRACE_INDEX_INIT)
626 System.out.println(getDescriptor() + "Initializing index at " + indexPath + " (overwrite = " + overwrite + ")");
627 mon.beginTask("Initializing Index", 100);
630 if (Files.exists(indexPath)) {
631 mon.subTask("Erasing previous index");
632 if (getLogger().isDebugEnabled())
633 getLogger().debug("Erasing previous index {}", indexPath.toAbsolutePath());
634 FileUtils.emptyDirectory(indexPath);
638 final AtomicReference<FSDirectory> directory = new AtomicReference<FSDirectory>();
639 final AtomicReference<IndexWriter> writer = new AtomicReference<IndexWriter>();
642 mon.subTask("Start index write");
643 Files.createDirectories(indexPath);
645 directory.set(FSDirectory.open(indexPath.toFile()));
646 IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_4_9, Queries.getAnalyzer()).setOpenMode(OpenMode.CREATE);
647 writer.set(new IndexWriter(directory.get(), conf));
651 long realizeStart = 0;
652 if (IndexPolicy.PERF_INDEX_INIT)
653 realizeStart = System.nanoTime();
655 mon.subTask("Calculating indexed content");
660 if (IndexPolicy.PERF_INDEX_INIT)
661 System.out.println(getDescriptor() + "Realized index with " + results.size() + " entries at " + indexPath + " in " + (1e-9 * (System.nanoTime()-realizeStart)) + " seconds.");
663 if (IndexPolicy.TRACE_INDEX_INIT)
664 System.out.println(getDescriptor() + "Indexed relation " + r + " produced " + results.size() + " results");
666 long start = IndexPolicy.PERF_INDEX_INIT ? System.nanoTime() : 0;
668 mon.subTask("Indexing content");
669 final Semaphore s = new Semaphore(0);
670 mon.setWorkRemaining(results.size());
671 for (int i = 0; i < INDEXING_THREAD_COUNT; i++) {
672 final int startIndex = i;
673 ThreadUtils.getBlockingWorkExecutor().submit(() -> {
675 Document document = new Document();
676 Field[] fs = makeFieldsForRelation(r, bound.length, document);
678 for (int index = startIndex; index < results.size(); index += INDEXING_THREAD_COUNT) {
679 if (setFields(fs, results.get(index)) == null)
682 writer.get().addDocument(document);
683 } catch (CorruptIndexException e) {
684 getLogger().error("Index is corrupted! {}", this, e);
685 throw new IllegalStateException(e);
686 } catch (IOException e) {
687 getLogger().error("Index is in problematic state! {}", this, e);
688 throw new IllegalStateException(e);
695 } catch (DatabaseException e) {
696 throw new IllegalStateException(e);
704 s.acquire(INDEXING_THREAD_COUNT);
705 } catch (InterruptedException e) {
706 getLogger().error("Could not initialize index {}", this, e);
709 // http://www.gossamer-threads.com/lists/lucene/java-dev/47895
710 // and http://lucene.apache.org/java/docs/index.html#27+November+2011+-+Lucene+Core+3.5.0
711 // advise against calling optimize at all. So let's not do it anymore.
712 //writer.get().optimize();
713 //writer.get().commit();
715 mon.subTask("Flushing");
717 if (IndexPolicy.PERF_INDEX_INIT)
718 System.out.println(getDescriptor() + "Wrote index at " + indexPath + " in " + (1e-9 * (System.nanoTime()-start)) + " seconds.");
720 result.complete(null);
721 // } catch (DatabaseException e) {
722 // getLogger().error("Could not initialize index due to db {}", this, e);
725 closeWriter(writer.getAndSet(null));
727 FileUtils.uncheckedClose(directory.getAndSet(null));
730 } catch (Throwable t) {
731 getLogger().error("Could not initialize index", t);
732 result.completeExceptionally(t);
737 public List<Object[]> debugDocs(IProgressMonitor monitor) throws ParseException, IOException, IndexingException {
739 Query query = new MatchAllDocsQuery();
741 TopDocs td = searcher.search(query, Integer.MAX_VALUE);
743 ScoreDoc[ ] scoreDocs = td.scoreDocs;
744 List<Object[]> result = new ArrayList<Object[]>(scoreDocs.length);
746 for(ScoreDoc scoreDoc:scoreDocs) {
750 Document doc = reader.document(scoreDoc.doc);
751 List<IndexableField> fs = doc.getFields();
752 Object[] o = new Object[fs.size()];
754 for (IndexableField f : fs) {
755 o[index++] = f.stringValue();
759 } catch (CorruptIndexException e) {
760 getLogger().error("Index is corrupted! {}", this, e);
761 throw new IndexCorruptedException("Index is corrupted! " + this, e);
762 } catch (IOException e) {
763 getLogger().error("Index is in problematic state! {}", this, e);
764 throw new IndexingException(e);
774 List<Map<String, Object>> doSearch(IProgressMonitor monitor, RequestProcessor processor, String search, int maxResultCount) throws ParseException, IOException,
777 // An empty search string will crash QueryParser
778 // Just return no results for empty queries.
779 //System.out.println("search: '" + search + "'");
780 if (search.isEmpty())
781 return Collections.emptyList();
783 assertAccessOpen(false);
785 Query query = Queries.parse(search, schema);
787 long start = System.nanoTime();
789 maxResultCount = Math.min(maxResultCount, searcher.getIndexReader().numDocs());
790 if (maxResultCount == 0)
791 return Collections.emptyList();
793 final TopDocs docs = searcher.search(query, null, maxResultCount);
795 // for(Object[] o : debugDocs(monitor)) {
796 // System.err.println("-" + Arrays.toString(o));
799 if (IndexPolicy.PERF_INDEX_QUERY) {
800 long end = System.nanoTime();
801 System.out.println(getDescriptor() + "search(" + search + ", " + maxResultCount + ") into index at " + indexPath + " took " + (1e-9 * (end-start)) + " seconds.");
804 if (docs.totalHits == 0) {
805 return Collections.emptyList();
809 return processor.syncRequest(new Read<List<Map<String, Object>>>() {
812 public List<Map<String, Object>> perform(ReadGraph graph) throws DatabaseException {
814 GenericRelation r = graph.adapt(relation, GenericRelation.class);
816 throw new IndexingException("Given resource " + graph.syncRequest(new SafeName(relation))
817 + "could not be adapted to GenericRelation.");
819 SerialisationSupport support = graph.getService(SerialisationSupport.class);
821 List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(docs.scoreDocs.length);
823 final DocumentStoredFieldVisitor visitor = new DocumentStoredFieldVisitor();
825 for (ScoreDoc scoreDoc : docs.scoreDocs) {
829 reader.document(scoreDoc.doc, visitor);
831 Document doc = visitor.getDocument();
833 List<IndexableField> fs = doc.getFields();
834 Map<String, Object> entry = new THashMap<String, Object>(fs.size());
835 for (IndexableField f : fs) {
836 IndexSchema.Type type = schema.typeMap.get(f.name());
837 if (type == IndexSchema.Type.LONG) {
838 entry.put(f.name(), support.getResource(f.numericValue().longValue()));
840 entry.put(f.name(), f.stringValue());
846 } catch (CorruptIndexException e) {
847 getLogger().error("Index is corrupted! {}", this, e);
848 throw new IndexCorruptedException("Index is corrupted! " + " " + this + " " + scoreDoc, e);
849 } catch (IOException e) {
850 getLogger().error("Index is in problematic state! {}", this, e);
851 throw new IndexingException(e);
857 } catch (DatabaseException e) {
858 if (e instanceof IndexingException) {
859 throw (IndexingException) e;
861 throw new IndexingException(e);
866 static class ResourceVisitor extends StoredFieldVisitor {
871 public Status needsField(FieldInfo fieldInfo) throws IOException {
872 if("Resource".equals(fieldInfo.name)) return Status.YES;
877 public void longField(FieldInfo fieldInfo, long value) throws IOException {
883 static class DumpVisitor extends StoredFieldVisitor {
885 public List<Object> values;
887 DumpVisitor(List<Object> values) {
888 this.values = values;
892 public Status needsField(FieldInfo fieldInfo) throws IOException {
897 public void longField(FieldInfo fieldInfo, long value) throws IOException {
902 public void stringField(FieldInfo fieldInfo, String value) throws IOException {
908 List<Resource> doSearchResources(IProgressMonitor monitor, RequestProcessor processor, String search, int maxResultCount) throws ParseException, IOException,
911 // An empty search string will crash QueryParser
912 // Just return no results for empty queries.
913 //System.out.println("search: '" + search + "'");
914 if (search.isEmpty())
915 return Collections.emptyList();
917 assertAccessOpen(false);
919 Query query = Queries.parse(search, schema);
921 long start = System.nanoTime();
923 maxResultCount = Math.min(maxResultCount, searcher.getIndexReader().numDocs());
924 if (maxResultCount == 0)
925 return Collections.emptyList();
927 final TopDocs docs = searcher.search(query, null, maxResultCount);
929 // for(Object[] o : debugDocs(monitor)) {
930 // System.err.println("-" + Arrays.toString(o));
933 if (IndexPolicy.PERF_INDEX_QUERY) {
934 long end = System.nanoTime();
935 System.out.println(getDescriptor() + "search(" + search + ", " + maxResultCount + ") into index at " + indexPath + " took " + (1e-9 * (end-start)) + " seconds.");
938 if (docs.totalHits == 0) {
939 return Collections.emptyList();
943 return processor.syncRequest(new Read<List<Resource>>() {
946 public List<Resource> perform(ReadGraph graph) throws DatabaseException {
948 CollectionSupport cs = graph.getService(CollectionSupport.class);
949 SerialisationSupport support = graph.getService(SerialisationSupport.class);
951 List<Resource> result = cs.createList();
953 ResourceVisitor visitor = new ResourceVisitor();
955 for (ScoreDoc scoreDoc : docs.scoreDocs) {
957 reader.document(scoreDoc.doc, visitor);
958 result.add(support.getResource(visitor.id));
959 } catch (CorruptIndexException e) {
960 getLogger().error("Index is corrupted! {}", this, e);
961 throw new IndexCorruptedException("Index is corrupted! " + " " + this + " " + scoreDoc, e);
962 } catch (IOException e) {
963 getLogger().error("Index is in problematic state! {}", this, e);
964 throw new IndexingException(e);
970 } catch (DatabaseException e) {
971 if (e instanceof IndexingException) {
972 throw (IndexingException) e;
974 throw new IndexingException(e);
979 List<Object> doList(IProgressMonitor monitor, RequestProcessor processor) throws ParseException, IOException,
982 assertAccessOpen(false);
984 Query query = new MatchAllDocsQuery();
986 final TopDocs docs = searcher.search(query, Integer.MAX_VALUE);
988 ArrayList<Object> result = new ArrayList<Object>();
990 DumpVisitor visitor = new DumpVisitor(result);
992 for (ScoreDoc scoreDoc : docs.scoreDocs) {
996 reader.document(scoreDoc.doc, visitor);
998 } catch (CorruptIndexException e) {
999 getLogger().error("Index is corrupted! {}", this, e);
1000 throw new IndexCorruptedException("Index is corrupted! " + " " + this + " " + scoreDoc, e);
1001 } catch (IOException e) {
1002 getLogger().error("Index is in problematic state! {}", this, e);
1003 throw new IndexingException(e);
1012 protected static Path getIndexDirectory(Session session, Resource relation, Resource input) {
1013 Path path = DatabaseIndexing.getIndexLocation(session, relation, input);
1014 // System.out.println("getIndexDirectory = " + path);
1018 Path getIndexPath() {
1022 boolean isIndexAvailable() {
1023 return Files.isDirectory(indexPath);
1026 abstract Throwable bestEffortClear(IProgressMonitor monitor, Session session);
1029 * Start from scratch. Clear all caches and rebuild the index.
1031 Throwable clearDirectory(IProgressMonitor monitor, Session session) {
1033 Path file = getIndexPath();
1036 FileUtils.delete(file);
1037 } catch (Throwable t) {
1038 getLogger().error("Could not delete directory {}", file.toAbsolutePath(), t);
1041 if (Files.exists(file))
1042 return new IllegalStateException("Failed to delete directory " + file.toAbsolutePath());
1046 private Field[] setFields(Field[] fs, Object[] result) {
1047 for (int i = 0; i < result.length; i++) {
1048 Object value = result[i];
1049 if (value instanceof String) {
1050 if (IndexPolicy.DEBUG_INDEX_INIT)
1051 System.out.println(getDescriptor() + "index " + fs[i].name() + " = " + value + " : String");
1052 fs[i].setStringValue((String) value);
1053 } else if (value instanceof Long) {
1054 if (IndexPolicy.DEBUG_INDEX_INIT)
1055 System.out.println(getDescriptor() + "index " + fs[i].name() + " = " + value + " : Long");
1056 fs[i].setLongValue((Long) value);
1058 getLogger().error("Can only index Long and String fields, encountered " + value);
1065 protected abstract Logger getLogger();
1068 public String toString() {
1069 return getClass().getSimpleName() + " [" + String.valueOf(schema) + ", " + String.valueOf(relation) + ", " + String.valueOf(input) + ", " + String.valueOf(indexPath) + ", " + String.valueOf(directory) + ", " + String.valueOf(state) + "]";