//Parse Query
Query parsedQuery;
SearchResponse response = new SearchResponse();
//Construct the multiSearcher
ParallelMultiSearcher multiSearcher = null;
RealTimeDiskFilter myFilter = null;
try{
//This section needs to be thread safe
synchronized(this){
//Commit any prev writes
if(hasWrite.getAndSet(false)){
ramWriter.commit();
//Reopen index reader
IndexReader newReader = ramReader.reopen();
if(ramReader != newReader){
//ramReader.close();
ramSearcher.close();
ramReader = newReader;
ramSearcher = new IndexSearcher(ramReader);
}
}
List<Searchable> searchersList = new ArrayList<Searchable>();
if(ramSearcher.maxDoc() > 0)
searchersList.add(ramSearcher);
if(prevRamSearcher != null && prevRamSearcher.maxDoc() > 0)
searchersList.add(prevRamSearcher);
if(diskSearcher.maxDoc() > 0)
searchersList.add(diskSearcher);
//empty index
if(searchersList.size() == 0)
return response;
Searchable[] searchers = new Searchable[]{};
multiSearcher = new ParallelMultiSearcher(searchersList.toArray(searchers));
myFilter = diskFilter;
}
PerFieldAnalyzerWrapper qAnalyzer = new PerFieldAnalyzerWrapper(analyzer);
QueryParser queryParser = new QueryParser(DOCUMENT_KEY,qAnalyzer);
//add any keyword fields
if(query.isSetKeyword_fields()){
for(String field : query.keyword_fields)
qAnalyzer.addAnalyzer(field, kwAnalyzer);
}
//parse query
//TODO: Cache?
try{
parsedQuery = queryParser.parse(query.getQuery());
}catch(org.apache.lucene.queryParser.ParseException e){
throw new ThrudexExceptionImpl(e.toString());
}
//Set Sort
Sort sortBy = new Sort();
if(query.isSetSortby() && !query.sortby.trim().equals(""))
sortBy.setSort(query.getSortby() + "_sort", query.desc);
//Search
TopDocs result = null;
try{
result = multiSearcher.search(parsedQuery,myFilter,query.offset + query.limit,sortBy);
}catch(Exception e){
logger.debug("Sortby failed, trying non sorted search");
result = multiSearcher.search(parsedQuery,myFilter,query.offset + query.limit);
}
response.setTotal(result.totalHits);
FieldSelector fieldSelector;
if(query.isPayload()){
fieldSelector = new MapFieldSelector(new String[]{DOCUMENT_KEY,PAYLOAD_KEY});
}else{
fieldSelector = new MapFieldSelector(new String[]{DOCUMENT_KEY});
}
for(int i=query.offset; i<result.totalHits && i<(query.offset + query.limit); i++){
Element el = new Element();
el.setIndex(query.index);
Document d = multiSearcher.doc(result.scoreDocs[i].doc,fieldSelector);
el.setKey(d.get(DOCUMENT_KEY));
if(query.isSetPayload() && query.payload)
el.setPayload(d.get(PAYLOAD_KEY));