List of usage examples for org.apache.solr.handler.component SearchComponent prepare
public abstract void prepare(ResponseBuilder rb) throws IOException;
From source file:com.search.MySearchHandler.java
License:Apache License
@Override public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception { // int sleep = req.getParams().getInt("sleep",0); // if (sleep > 0) {log.error("SLEEPING for " + sleep); // Thread.sleep(sleep);} /*** Pre-processing of the Query by REGEX starts here -------------- ***/ SolrParams originalParams = req.getOriginalParams(); SolrParams psuedoParams = req.getParams(); // These psuedoParams keep // changing// w ww . ja v a2 s .co m if (originalParams.get(CommonParams.Q) != null) { String finalQuery; String originalQuery = originalParams.get(CommonParams.Q); rsp.add("Original query", originalQuery); SchemaField keyField = null; keyField = req.getCore().getLatestSchema().getUniqueKeyField(); if (keyField != null) { fieldSet.add(keyField.getName()); } /*** * START CODE TO PARSE QUERY * * Arafath's code to prepare query starts here The query should be * in the following format -> * * * * Example : Original Query: * "Which musical object did russ conway play" Temporary Query : * "relations:instrument AND entity:enty" // Generate the relation * Final Query : "name:"russ conway" AND occupation:musician" */ ParsedQuestion parsedq = new ParsedQuestion(); parsedq = parseQues(originalQuery); if (parsedq != null) { System.out.println(parsedq); Map<Integer, String> relationstr = getRelation(parsedq.getRelationKeyWord(), parsedq.getWhtype(), req); /** * END CODE TO PARSE QUERY */ /*** Final Phase starts here ***/ finalQuery = "title:\"" + parsedq.getSearchName() + "\""; NamedList finalparamsList = req.getParams().toNamedList(); finalparamsList.setVal(finalparamsList.indexOf(CommonParams.Q, 0), finalQuery); psuedoParams = SolrParams.toSolrParams(finalparamsList); if (psuedoParams.get(CommonParams.SORT) == null) { finalparamsList.add(CommonParams.SORT, "score desc"); } else { finalparamsList.setVal(finalparamsList.indexOf(CommonParams.SORT, 0), "score desc"); } int documentsRetrieved = 0; if (relationstr != null) { rsp.add("total relations retrieved", relationstr.size()); rsp.add("relations", relationstr); NamedList finaldocresults = new NamedList(); NamedList forwarddocresults = new NamedList(); Set<String> checkDocuments = new HashSet<String>(); for (int i = 0; i < relationstr.size() && (documentsRetrieved < 10); i++) { NamedList relationdocresults = new NamedList(); String desiredField = relationstr.get(i); Set<String> tempFieldSet = new HashSet<String>(); int docsRetrievedforThisRelation = 0; tempFieldSet.add(desiredField); psuedoParams = SolrParams.toSolrParams(finalparamsList); if (psuedoParams.get(CommonParams.FL) == null) { finalparamsList.add(CommonParams.FL, desiredField); } else { finalparamsList.setVal(finalparamsList.indexOf(CommonParams.FL, 0), desiredField); } SolrQueryRequest finalreq = new LocalSolrQueryRequest(req.getCore(), finalparamsList); rsp.add("Final Query", finalreq.getParams().get(CommonParams.Q)); SolrQueryResponse finalrsp = new SolrQueryResponse(); ResponseBuilder finalrb = new ResponseBuilder(finalreq, finalrsp, components); for (SearchComponent c : components) { c.prepare(finalrb); c.process(finalrb); } DocList finaldocs = finalrb.getResults().docList; if (finaldocs == null || finaldocs.size() == 0) { log.debug("No results"); // support for reverse query } else { DocIterator finaliterator = finaldocs.iterator(); Document finaldoc; for (int j = 0; j < finaldocs.size(); j++) { try { if (finaliterator.hasNext()) { int finaldocid = finaliterator.nextDoc(); finaldoc = finalrb.req.getSearcher().doc(finaldocid, tempFieldSet); if (!checkDocuments.contains(finaldoc.get("id"))) { if (finaldoc.get(desiredField) != null) { checkDocuments.add(finaldoc.get("id")); docsRetrievedforThisRelation++; documentsRetrieved++; relationdocresults.add(finaldoc.get("title"), finaldoc); if (documentsRetrieved >= 10) { break; } } } } } catch (IOException ex) { java.util.logging.Logger.getLogger(MySearchHandler.class.getName()) .log(Level.SEVERE, null, ex); } } if (docsRetrievedforThisRelation > 0) { rsp.add("docs retrieved for : " + desiredField, docsRetrievedforThisRelation); forwarddocresults.add(desiredField, relationdocresults); } } finalreq.close(); if (documentsRetrieved > 0) { rsp.add("type", "forward"); rsp.add("final results", forwarddocresults); } } if (documentsRetrieved == 0) { NamedList reversedocresults = new NamedList(); relationstr = getRelationReverse(parsedq.getRelationKeyWord(), req); System.out.println(relationstr); StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_46); String reversequery = ""; for (int i = 0; i < relationstr.size(); i++) { QueryParser relationsparser = new QueryParser(Version.LUCENE_46, relationstr.get(i), analyzer); try { reversequery += relationsparser.parse(parsedq.getSearchName()).toString() + " "; } catch (ParseException e) { e.printStackTrace(); } } QueryParser relationsparser = new QueryParser(Version.LUCENE_46, "infotype", analyzer); reversequery += relationsparser.parse(parsedq.getWhtype().firstKey().toLowerCase()); NamedList reverseList = req.getParams().toNamedList(); psuedoParams = SolrParams.toSolrParams(reverseList); reverseList.setVal(reverseList.indexOf(CommonParams.Q, 0), reversequery); SolrQueryRequest reversereq = new LocalSolrQueryRequest(req.getCore(), reverseList); SolrQueryResponse reversersp = new SolrQueryResponse(); ResponseBuilder reverserb = new ResponseBuilder(reversereq, reversersp, components); for (SearchComponent c : components) { try { c.prepare(reverserb); c.process(reverserb); } catch (IOException ex) { java.util.logging.Logger.getLogger(MySearchHandler.class.getName()) .log(Level.SEVERE, null, ex); } } DocList reversedocs = reverserb.getResults().docList; if (reversedocs == null || reversedocs.size() == 0) { log.debug("No results"); // GET SECOND entry from WHTYPE .. search with that .. } else { // NamedList docresults = new NamedList(); DocIterator reverseiterator = reversedocs.iterator(); Document reversedoc; int docScore = 0; for (int m = 0; m < reversedocs.size(); m++) { try { int reversedocid = reverseiterator.nextDoc(); reversedoc = reverserb.req.getSearcher().doc(reversedocid, fieldSet); if (reversedoc.get("title") != null) { documentsRetrieved++; reversedocresults.add(reversedoc.get("title"), reversedoc); if (documentsRetrieved >= 10) { break; } } } catch (IOException ex) { java.util.logging.Logger.getLogger(MySearchHandler.class.getName()) .log(Level.SEVERE, null, ex); } } } if (documentsRetrieved == 0) { rsp.add("message", "No Results found. Try another query!"); } else { rsp.add("type", "reverse"); rsp.add("final results", reversedocresults); } reversereq.close(); } } else { if (documentsRetrieved == 0) { rsp.add("message", "No Results found. Please rephrase the query!"); } } } else { rsp.add("message", "This is not a valid query!"); } } else { rsp.add("message", "User should provide at least one word as a query!"); } }
From source file:com.search.MySearchHandler.java
License:Apache License
private Map<Integer, String> getRelationReverse(String value, SolrQueryRequest req) { /*** Galla's modified code starts here ---- > * // ww w . jav a2 s . c o m */ StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_46); QueryParser relationsparser = new QueryParser(Version.LUCENE_46, "relations", analyzer); QueryParser entityparser = new QueryParser(Version.LUCENE_46, "entity", analyzer); QueryParser fieldidparser = new QueryParser(Version.LUCENE_46, "fieldid", analyzer); Map<Integer, String> desiredFieldList = null; int desiredFieldsCount = 0; String desiredRelation = null; Set<String> checkRelation = null; if (desiredFieldsCount < 5) { desiredFieldList = new HashMap<Integer, String>(); checkRelation = new HashSet<String>(); NamedList tempparamsList = req.getParams().toNamedList(); SolrParams psuedoParams = SolrParams.toSolrParams(tempparamsList); if (psuedoParams.get(CommonParams.SORT) == null) { tempparamsList.add(CommonParams.SORT, "score desc"); } else { tempparamsList.setVal(tempparamsList.indexOf(CommonParams.SORT, 0), "score desc"); } SolrQueryRequest firstreq = null; SolrQueryResponse firstrsp = null; ResponseBuilder firstrb = null; DocList docs = null; String relString = ""; String fieldString = ""; try { relString = relationsparser.parse(value).toString(); fieldString = fieldidparser.parse(value).toString(); } catch (ParseException e) { e.printStackTrace(); } // (+relations:"children" and +entity:"num") or (relations:"children" and fieldid:"children") or (fieldid:"children" and entity:"num") String tempQuery = "(" + relString + ")" + " OR (" + fieldString + ")"; System.out.println(tempQuery); tempparamsList.setVal(tempparamsList.indexOf(CommonParams.Q, 0), tempQuery); firstreq = new LocalSolrQueryRequest(req.getCore(), tempparamsList); firstrsp = new SolrQueryResponse(); firstrb = new ResponseBuilder(firstreq, firstrsp, components); for (SearchComponent c : components) { try { c.prepare(firstrb); c.process(firstrb); } catch (IOException ex) { java.util.logging.Logger.getLogger(MySearchHandler.class.getName()).log(Level.SEVERE, null, ex); } } docs = firstrb.getResults().docList; if (docs == null || docs.size() == 0) { log.debug("No results"); // GET SECOND entry from WHTYPE .. search with that .. } else { // NamedList docresults = new NamedList(); DocIterator iterator = docs.iterator(); Document doc; int docScore = 0; for (int i = 0; i < docs.size(); i++) { try { int docid = iterator.nextDoc(); doc = firstrb.req.getSearcher().doc(docid, fieldSet); desiredRelation = doc.get("fieldid"); if (!checkRelation.contains(desiredRelation)) { checkRelation.add(desiredRelation); desiredFieldList.put(desiredFieldsCount++, desiredRelation); System.out.println("vgalla's relation : " + desiredRelation); if (desiredFieldsCount >= 5) { return desiredFieldList; } } } catch (IOException ex) { java.util.logging.Logger.getLogger(MySearchHandler.class.getName()).log(Level.SEVERE, null, ex); } } } firstreq.close(); /*** Galla's code ends here ----- > * */ } return desiredFieldList; }
From source file:com.search.MySearchHandler.java
License:Apache License
private static Map<Integer, String> getRelation(String value, TreeMap<String, Double> whtype, SolrQueryRequest req) {/*from w w w .ja va 2 s . c om*/ /*** * Galla's modified code starts here ---- > * */ Map<Integer, String> desiredFieldList = null; if (whtype != null) { StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_46); QueryParser relationsparser = new QueryParser(Version.LUCENE_46, "relations", analyzer); QueryParser entityparser = new QueryParser(Version.LUCENE_46, "entity", analyzer); QueryParser fieldidparser = new QueryParser(Version.LUCENE_46, "fieldid", analyzer); int desiredFieldsCount = 0; String desiredRelation = null; Set<String> whtypeSet = whtype.keySet(); Set<String> checkRelation = null; if (!whtypeSet.isEmpty() && (desiredFieldsCount < 5)) { desiredFieldList = new HashMap<Integer, String>(); checkRelation = new HashSet<String>(); NamedList tempparamsList = req.getParams().toNamedList(); SolrParams psuedoParams = SolrParams.toSolrParams(tempparamsList); if (psuedoParams.get(CommonParams.SORT) == null) { tempparamsList.add(CommonParams.SORT, "score desc"); } else { tempparamsList.setVal(tempparamsList.indexOf(CommonParams.SORT, 0), "score desc"); } SolrQueryRequest firstreq = null; SolrQueryResponse firstrsp = null; ResponseBuilder firstrb = null; DocList docs = null; for (String tempStr : whtypeSet) { String tempType = tempStr.toLowerCase().trim(); String relString = ""; String entyString = ""; String fieldString = ""; try { relString = relationsparser.parse(value).toString(); entyString = entityparser.parse(tempType).toString(); fieldString = fieldidparser.parse(value).toString(); } catch (ParseException e) { e.printStackTrace(); } // (+relations:"children" and +entity:"num") or // (relations:"children" and fieldid:"children") or // (fieldid:"children" and entity:"num") String tempQuery = "(" + relString + " AND " + entyString + ")" + " OR " + "(" + relString + " AND " + fieldString + ")" + " OR " + "(" + fieldString + " AND " + entyString + ")"; System.out.println(tempQuery); tempparamsList.setVal(tempparamsList.indexOf(CommonParams.Q, 0), tempQuery); firstreq = new LocalSolrQueryRequest(req.getCore(), tempparamsList); firstrsp = new SolrQueryResponse(); firstrb = new ResponseBuilder(firstreq, firstrsp, components); for (SearchComponent c : components) { try { c.prepare(firstrb); c.process(firstrb); } catch (IOException ex) { java.util.logging.Logger.getLogger(MySearchHandler.class.getName()).log(Level.SEVERE, null, ex); } } docs = firstrb.getResults().docList; if (docs == null || docs.size() == 0) { log.debug("No results"); // GET SECOND entry from WHTYPE .. search with that .. } else { // NamedList docresults = new NamedList(); DocIterator iterator = docs.iterator(); Document doc; int docScore = 0; for (int i = 0; i < docs.size(); i++) { try { int docid = iterator.nextDoc(); doc = firstrb.req.getSearcher().doc(docid, fieldSet); desiredRelation = doc.get("fieldid"); if (!checkRelation.contains(desiredRelation)) { checkRelation.add(desiredRelation); desiredFieldList.put(desiredFieldsCount++, desiredRelation); System.out.println("vgalla's relation : " + desiredRelation); if (desiredFieldsCount >= 5) { return desiredFieldList; } } } catch (IOException ex) { java.util.logging.Logger.getLogger(MySearchHandler.class.getName()) .log(Level.SEVERE, null, ex); } } } firstreq.close(); /*** * Galla's code ends here ----- > * */ String exrelstring = ""; String[] strarray = value.split(" "); for (int i = 0; i < strarray.length; i++) { if (exrelmap.containsKey(strarray[i].toLowerCase().trim())) { exrelstring += exrelmap.get(strarray[i].toLowerCase().trim()); } } if (!exrelstring.equals("")) { String[] temp = exrelstring.split("~~"); for (int i = 0; i < temp.length; i++) { if (!temp[i].trim().equals("")) { String mapdetect = mappingmap.get(temp[i].trim()); if (mapdetect.toLowerCase().trim().equals(tempType)) { desiredRelation = temp[i].trim(); if (!checkRelation.contains(desiredRelation)) { checkRelation.add(desiredRelation); desiredFieldList.put(desiredFieldsCount++, desiredRelation); System.out.println("arafath's relation : " + desiredRelation); if (desiredFieldsCount >= 5) { return desiredFieldList; } } } } } } } } } return desiredFieldList; }
From source file:com.search.MySearchHandlerTest.java
License:Apache License
@Override public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception { // int sleep = req.getParams().getInt("sleep",0); // if (sleep > 0) {log.error("SLEEPING for " + sleep); Thread.sleep(sleep);} /*** Pre-processing of the Query by REGEX starts here --------------***/ SolrParams originalParams = req.getOriginalParams(); SolrParams psuedoParams = req.getParams(); // These psuedoParams keep changing if (originalParams.get(CommonParams.Q) != null) { String finalQuery;//from www. j a v a2 s . c o m String originalQuery = originalParams.get(CommonParams.Q); rsp.add("Original query", originalQuery); /*** Arafath's code to prepare query starts here * The query should be in the following format -> * Example : * Original Query: "Which musical object did russ conway play" * Temporary Query : "relations:instrument AND entity:enty" // Generate the relation * Final Query : "name:"russ conway" AND occupation:musician" */ String tempQuery = "relations:instrumental AND entity:enty"; rsp.add("Temporary query", tempQuery); String desiredField = null; Set<String> fieldSet = null; SchemaField keyField = null; NamedList tempparamsList = req.getParams().toNamedList(); tempparamsList.setVal(tempparamsList.indexOf(CommonParams.Q, 0), tempQuery); psuedoParams = SolrParams.toSolrParams(tempparamsList); // if (psuedoParams.get(CommonParams.SORT) == null) { // tempparamsList.add(CommonParams.SORT, "score desc"); // } else { // tempparamsList.setVal(tempparamsList.indexOf(CommonParams.SORT, 0), "score desc"); // } SolrQueryRequest firstreq = new LocalSolrQueryRequest(req.getCore(), tempparamsList); SolrQueryResponse firstrsp = new SolrQueryResponse(); firstrsp.setAllValues(rsp.getValues()); ResponseBuilder firstrb = new ResponseBuilder(firstreq, firstrsp, components); for (SearchComponent c : components) { c.prepare(firstrb); c.process(firstrb); } rsp.add("response", firstrb.getResults().docList); /*** DocList docs = firstrb.getResults().docList; if (docs == null || docs.size() == 0) { log.debug("No results"); } else { fieldSet = new HashSet <String> (); keyField = firstrb.req.getCore().getLatestSchema().getUniqueKeyField(); if (keyField != null) { fieldSet.add(keyField.getName()); } fieldSet.add("fieldid"); fieldSet.add("relations"); fieldSet.add("entity"); fieldSet.add("count"); NamedList docresults = new NamedList(); DocIterator iterator = docs.iterator(); Document doc; int docScore = 0; rsp.add("doc retrieved ", docs.size()); for (int i=0; i<docs.size(); i++) { try { int docid = iterator.nextDoc(); doc = firstrb.req.getSearcher().doc(docid, fieldSet); if (Integer.parseInt(doc.get("count")) > docScore) { docScore = Integer.parseInt(doc.get("count")); desiredField = doc.get("fieldid"); } docresults.add(String.valueOf(docid), doc); } catch (IOException ex) { java.util.logging.Logger.getLogger(CustomQueryComponent.class.getName()).log(Level.SEVERE, null,ex); } } fieldSet.clear(); rsp.add("Intermediate results", docresults); if (desiredField != null) { rsp.add("Required Field", desiredField); } } ***/ firstreq.close(); /*** Final Phase starts here ***/ /*** finalQuery = "name:\"russ conway\" AND occupation:musician"; NamedList finalparamsList = req.getParams().toNamedList(); finalparamsList.setVal(finalparamsList.indexOf(CommonParams.Q, 0), finalQuery); psuedoParams = SolrParams.toSolrParams(finalparamsList); if (psuedoParams.get(CommonParams.SORT) == null) { finalparamsList.add(CommonParams.SORT, "score desc"); } else { finalparamsList.setVal(finalparamsList.indexOf(CommonParams.SORT, 0), "score desc"); } // if (desiredField != null) { // if (psuedoParams.get(CommonParams.FL) != null) { // finalparamsList.setVal(finalparamsList.indexOf(CommonParams.FL, 0), desiredField); // } else { // finalparamsList.add(CommonParams.FL, desiredField); // } // } SolrQueryRequest finalreq = new LocalSolrQueryRequest(req.getCore(), finalparamsList); rsp.add("Final Query", finalreq.getParams().get(CommonParams.Q)); ResponseBuilder rb = new ResponseBuilder(finalreq,rsp,components); for (SearchComponent c : components) { c.prepare(rb); c.process(rb); } ***/ /*** testing DocList finaldocs = rb.getResults().docList; if (finaldocs == null || finaldocs.size() == 0) { log.debug("No results"); } else { keyField = rb.req.getCore().getLatestSchema().getUniqueKeyField(); if (keyField != null) { fieldSet.add(keyField.getName()); } if (desiredField != null) { fieldSet.add(desiredField); } fieldSet.add("name"); NamedList finaldocresults = new NamedList(); DocIterator finaliterator = finaldocs.iterator(); Document finaldoc; rsp.add("finaldocs retrieved ", finaldocs.size()); for (int i=0; i<docs.size(); i++) { try { if (finaliterator.hasNext()) { int finaldocid = finaliterator.nextDoc(); finaldoc = rb.req.getSearcher().doc(finaldocid, fieldSet); finaldocresults.add(String.valueOf(finaldocid), finaldoc); } } catch (IOException ex) { java.util.logging.Logger.getLogger(MySearchHandler.class.getName()).log(Level.SEVERE, null,ex); } } rsp.add("final results", finaldocresults); } ***/ // finalreq.close(); } else { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Need to give at least one word as query!"); } }
From source file:org.opencms.search.solr.CmsSolrIndex.java
License:Open Source License
/** * Performs the actual search.<p>/*from w w w . ja v a 2 s . com*/ * * @param cms the current OpenCms context * @param ignoreMaxRows <code>true</code> to return all all requested rows, <code>false</code> to use max rows * @param query the OpenCms Solr query * @param response the servlet response to write the query result to, may also be <code>null</code> * @param ignoreSearchExclude if set to false, only contents with search_exclude unset or "false" will be found - typical for the the non-gallery case * @param filter the resource filter to use * * @return the found documents * * @throws CmsSearchException if something goes wrong * * @see #search(CmsObject, CmsSolrQuery, boolean) */ @SuppressWarnings("unchecked") public CmsSolrResultList search(CmsObject cms, final CmsSolrQuery query, boolean ignoreMaxRows, ServletResponse response, boolean ignoreSearchExclude, CmsResourceFilter filter) throws CmsSearchException { // check if the user is allowed to access this index checkOfflineAccess(cms); if (!ignoreSearchExclude) { query.addFilterQuery(CmsSearchField.FIELD_SEARCH_EXCLUDE + ":\"false\""); } int previousPriority = Thread.currentThread().getPriority(); long startTime = System.currentTimeMillis(); // remember the initial query SolrQuery initQuery = query.clone(); query.setHighlight(false); LocalSolrQueryRequest solrQueryRequest = null; try { // initialize the search context CmsObject searchCms = OpenCms.initCmsObject(cms); // change thread priority in order to reduce search impact on overall system performance if (getPriority() > 0) { Thread.currentThread().setPriority(getPriority()); } // the lists storing the found documents that will be returned List<CmsSearchResource> resourceDocumentList = new ArrayList<CmsSearchResource>(); SolrDocumentList solrDocumentList = new SolrDocumentList(); // Initialize rows, offset, end and the current page. int rows = query.getRows() != null ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue(); if (!ignoreMaxRows && (rows > ROWS_MAX)) { rows = ROWS_MAX; } int start = query.getStart() != null ? query.getStart().intValue() : 0; int end = start + rows; int page = 0; if (rows > 0) { page = Math.round(start / rows) + 1; } // set the start to '0' and expand the rows before performing the query query.setStart(new Integer(0)); query.setRows(new Integer((5 * rows * page) + start)); // perform the Solr query and remember the original Solr response QueryResponse queryResponse = m_solr.query(query); long solrTime = System.currentTimeMillis() - startTime; // initialize the counts long hitCount = queryResponse.getResults().getNumFound(); start = -1; end = -1; if ((rows > 0) && (page > 0) && (hitCount > 0)) { // calculate the final size of the search result start = rows * (page - 1); end = start + rows; // ensure that both i and n are inside the range of foundDocuments.size() start = new Long((start > hitCount) ? hitCount : start).intValue(); end = new Long((end > hitCount) ? hitCount : end).intValue(); } else { // return all found documents in the search result start = 0; end = new Long(hitCount).intValue(); } long visibleHitCount = hitCount; float maxScore = 0; // If we're using a postprocessor, (re-)initialize it before using it if (m_postProcessor != null) { m_postProcessor.init(); } // process found documents List<CmsSearchResource> allDocs = new ArrayList<CmsSearchResource>(); int cnt = 0; for (int i = 0; (i < queryResponse.getResults().size()) && (cnt < end); i++) { try { SolrDocument doc = queryResponse.getResults().get(i); CmsSolrDocument searchDoc = new CmsSolrDocument(doc); if (needsPermissionCheck(searchDoc)) { // only if the document is an OpenCms internal resource perform the permission check CmsResource resource = filter == null ? getResource(searchCms, searchDoc) : getResource(searchCms, searchDoc, filter); if (resource != null) { // permission check performed successfully: the user has read permissions! if (cnt >= start) { if (m_postProcessor != null) { doc = m_postProcessor.process(searchCms, resource, (SolrInputDocument) searchDoc.getDocument()); } resourceDocumentList.add(new CmsSearchResource(resource, searchDoc)); if (null != doc) { solrDocumentList.add(doc); } maxScore = maxScore < searchDoc.getScore() ? searchDoc.getScore() : maxScore; } allDocs.add(new CmsSearchResource(resource, searchDoc)); cnt++; } else { visibleHitCount--; } } else { // if permission check is not required for this index, // add a pseudo resource together with document to the results resourceDocumentList.add(new CmsSearchResource(PSEUDO_RES, searchDoc)); solrDocumentList.add(doc); maxScore = maxScore < searchDoc.getScore() ? searchDoc.getScore() : maxScore; cnt++; } } catch (Exception e) { // should not happen, but if it does we want to go on with the next result nevertheless LOG.warn(Messages.get().getBundle().key(Messages.LOG_SOLR_ERR_RESULT_ITERATION_FAILED_0), e); } } // the last documents were all secret so let's take the last found docs if (resourceDocumentList.isEmpty() && (allDocs.size() > 0)) { page = Math.round(allDocs.size() / rows) + 1; int showCount = allDocs.size() % rows; showCount = showCount == 0 ? rows : showCount; start = allDocs.size() - new Long(showCount).intValue(); end = allDocs.size(); if (allDocs.size() > start) { resourceDocumentList = allDocs.subList(start, end); for (CmsSearchResource r : resourceDocumentList) { maxScore = maxScore < r.getDocument().getScore() ? r.getDocument().getScore() : maxScore; solrDocumentList.add(((CmsSolrDocument) r.getDocument()).getSolrDocument()); } } } long processTime = System.currentTimeMillis() - startTime - solrTime; // create and return the result solrDocumentList.setStart(start); solrDocumentList.setMaxScore(new Float(maxScore)); solrDocumentList.setNumFound(visibleHitCount); queryResponse.getResponse().setVal(queryResponse.getResponse().indexOf(QUERY_RESPONSE_NAME, 0), solrDocumentList); queryResponse.getResponseHeader().setVal(queryResponse.getResponseHeader().indexOf(QUERY_TIME_NAME, 0), new Integer(new Long(System.currentTimeMillis() - startTime).intValue())); long highlightEndTime = System.currentTimeMillis(); SolrCore core = m_solr instanceof EmbeddedSolrServer ? ((EmbeddedSolrServer) m_solr).getCoreContainer().getCore(getCoreName()) : null; CmsSolrResultList result = null; try { SearchComponent highlightComponenet = null; if (core != null) { highlightComponenet = core.getSearchComponent("highlight"); solrQueryRequest = new LocalSolrQueryRequest(core, queryResponse.getResponseHeader()); } SolrQueryResponse solrQueryResponse = null; if (solrQueryRequest != null) { // create and initialize the solr response solrQueryResponse = new SolrQueryResponse(); solrQueryResponse.setAllValues(queryResponse.getResponse()); int paramsIndex = queryResponse.getResponseHeader().indexOf(HEADER_PARAMS_NAME, 0); NamedList<Object> header = null; Object o = queryResponse.getResponseHeader().getVal(paramsIndex); if (o instanceof NamedList) { header = (NamedList<Object>) o; header.setVal(header.indexOf(CommonParams.ROWS, 0), new Integer(rows)); header.setVal(header.indexOf(CommonParams.START, 0), new Long(start)); } // set the OpenCms Solr query as parameters to the request solrQueryRequest.setParams(initQuery); // perform the highlighting if ((header != null) && (initQuery.getHighlight()) && (highlightComponenet != null)) { header.add(HighlightParams.HIGHLIGHT, "on"); if ((initQuery.getHighlightFields() != null) && (initQuery.getHighlightFields().length > 0)) { header.add(HighlightParams.FIELDS, CmsStringUtil.arrayAsString(initQuery.getHighlightFields(), ",")); } String formatter = initQuery.getParams(HighlightParams.FORMATTER) != null ? initQuery.getParams(HighlightParams.FORMATTER)[0] : null; if (formatter != null) { header.add(HighlightParams.FORMATTER, formatter); } if (initQuery.getHighlightFragsize() != 100) { header.add(HighlightParams.FRAGSIZE, new Integer(initQuery.getHighlightFragsize())); } if (initQuery.getHighlightRequireFieldMatch()) { header.add(HighlightParams.FIELD_MATCH, new Boolean(initQuery.getHighlightRequireFieldMatch())); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(initQuery.getHighlightSimplePost())) { header.add(HighlightParams.SIMPLE_POST, initQuery.getHighlightSimplePost()); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(initQuery.getHighlightSimplePre())) { header.add(HighlightParams.SIMPLE_PRE, initQuery.getHighlightSimplePre()); } if (initQuery.getHighlightSnippets() != 1) { header.add(HighlightParams.SNIPPETS, new Integer(initQuery.getHighlightSnippets())); } ResponseBuilder rb = new ResponseBuilder(solrQueryRequest, solrQueryResponse, Collections.singletonList(highlightComponenet)); try { rb.doHighlights = true; DocListAndSet res = new DocListAndSet(); SchemaField idField = OpenCms.getSearchManager().getSolrServerConfiguration() .getSolrSchema().getUniqueKeyField(); int[] luceneIds = new int[rows]; int docs = 0; for (SolrDocument doc : solrDocumentList) { String idString = (String) doc.getFirstValue(CmsSearchField.FIELD_ID); int id = solrQueryRequest.getSearcher().getFirstMatch( new Term(idField.getName(), idField.getType().toInternal(idString))); luceneIds[docs++] = id; } res.docList = new DocSlice(0, docs, luceneIds, null, docs, 0); rb.setResults(res); rb.setQuery(QParser.getParser(initQuery.getQuery(), null, solrQueryRequest).getQuery()); rb.setQueryString(initQuery.getQuery()); highlightComponenet.prepare(rb); highlightComponenet.process(rb); highlightComponenet.finishStage(rb); } catch (Exception e) { LOG.error(e.getMessage() + " in query: " + initQuery, new Exception(e)); } // Make highlighting also available via the CmsSolrResultList queryResponse.setResponse(solrQueryResponse.getValues()); highlightEndTime = System.currentTimeMillis(); } } result = new CmsSolrResultList(initQuery, queryResponse, solrDocumentList, resourceDocumentList, start, new Integer(rows), end, page, visibleHitCount, new Float(maxScore), startTime, highlightEndTime); if (LOG.isDebugEnabled()) { Object[] logParams = new Object[] { new Long(System.currentTimeMillis() - startTime), new Long(result.getNumFound()), new Long(solrTime), new Long(processTime), new Long(result.getHighlightEndTime() != 0 ? result.getHighlightEndTime() - startTime : 0) }; LOG.debug(query.toString() + "\n" + Messages.get().getBundle().key(Messages.LOG_SOLR_SEARCH_EXECUTED_5, logParams)); } if (response != null) { writeResp(response, solrQueryRequest, solrQueryResponse); } } finally { if (solrQueryRequest != null) { solrQueryRequest.close(); } if (core != null) { core.close(); } } return result; } catch (Exception e) { throw new CmsSearchException(Messages.get().container(Messages.LOG_SOLR_ERR_SEARCH_EXECUTION_FAILD_1, CmsEncoder.decode(query.toString()), e), e); } finally { if (solrQueryRequest != null) { solrQueryRequest.close(); } // re-set thread to previous priority Thread.currentThread().setPriority(previousPriority); } }