List of usage examples for org.apache.solr.response SolrQueryResponse getValues
public NamedList getValues()
From source file:alba.components.FilteredShowFileRequestHandler.java
License:Apache License
private void showFromZooKeeper(SolrQueryRequest req, SolrQueryResponse rsp, CoreContainer coreContainer) throws KeeperException, InterruptedException, UnsupportedEncodingException { SolrZkClient zkClient = coreContainer.getZkController().getZkClient(); String adminFile = getAdminFileFromZooKeeper(req, rsp, zkClient, hiddenFiles); if (adminFile == null) { return;/* w ww . j a va2 s .c om*/ } // Show a directory listing List<String> children = zkClient.getChildren(adminFile, null, true); if (children.size() > 0) { NamedList<SimpleOrderedMap<Object>> files = new SimpleOrderedMap<>(); for (String f : children) { if (isHiddenFile(req, rsp, f, false, hiddenFiles)) { continue; } SimpleOrderedMap<Object> fileInfo = new SimpleOrderedMap<>(); files.add(f, fileInfo); List<String> fchildren = zkClient.getChildren(adminFile + "/" + f, null, true); if (fchildren.size() > 0) { fileInfo.add("directory", true); } else { // TODO? content type fileInfo.add("size", f.length()); } // TODO: ? // fileInfo.add( "modified", new Date( f.lastModified() ) ); } rsp.add("files", files); } else { // Include the file contents // The file logic depends on RawResponseWriter, so force its use. ModifiableSolrParams params = new ModifiableSolrParams(req.getParams()); params.set(CommonParams.WT, "raw"); req.setParams(params); ContentStreamBase content = new ContentStreamBase.ByteArrayStream( zkClient.getData(adminFile, null, null, true), adminFile); content.setContentType(req.getParams().get(USE_CONTENT_TYPE)); // Velocity parsing here! // http://velocity.apache.org/engine/devel/developer-guide.html#The_Context Velocity.init(); VelocityContext context = new VelocityContext(); //add some vars?? //context.put( "context", new String("Velocity") ); for (int i = 0; i < rsp.getValues().size(); i++) { context.put(rsp.getValues().getName(i), rsp.getValues().getVal(i)); } Template template = null; String fname = req.getParams().get("file", null); try { //TODO what if fname is null? template = Velocity.getTemplate(fname); } catch (ResourceNotFoundException rnfe) { // couldn't find the template, try to load it // TODO it should be fired only for SOME mimetypes (..through an annotation??) StringBuilder sb = this.getTemplate(content); RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices(); StringReader reader = new StringReader(sb.toString()); SimpleNode node = null; try { node = runtimeServices.parse(reader, fname); } catch (ParseException e) { // TODO Auto-generated catch block logger.error("error while parsing new template", e); } template = new Template(); template.setRuntimeServices(runtimeServices); if (node != null) { template.setData(node); } else { logger.error("node null, can't set on template"); } template.initDocument(); } catch (ParseErrorException pee) { // syntax error: problem parsing the template logger.error("error while parsing template: ", pee); } catch (MethodInvocationException mie) { // something invoked in the template // threw an exception logger.error("error while parsing temaplate: ", mie); } catch (Exception e) { logger.error("error while parsing temaplate: ", e); } StringWriter sw = new StringWriter(); template.merge(context, sw); // http://stackoverflow.com/questions/18571223/how-to-convert-java-string-into-byte content = new ContentStreamBase.ByteArrayStream( sw.getBuffer().toString().getBytes(Charset.forName("UTF-8")), adminFile); content.setContentType(req.getParams().get(USE_CONTENT_TYPE)); rsp.add(RawResponseWriter.CONTENT, content); } rsp.setHttpCaching(false); }
From source file:alba.solr.common.MySimpleFloatFunction.java
License:Apache License
@ResponseWriter(value = "alba", responseType = "text/plain") public void myResponseWriter(Writer writer, SolrQueryRequest request, SolrQueryResponse response) throws IOException { writer.write("<h1>hello world!</h1>\n\r"); writer.write(response.getValues().toString()); }
From source file:at.newmedialab.lmf.util.solr.suggestion.result.SuggestionResultFactory.java
License:Apache License
@SuppressWarnings({ "rawtypes", "unchecked" })
private static SuggestionResult filterSingleValue(SolrCore core, SolrQueryResponse rsp, String[] fields,
String query, String df) {
SuggesionResultSingle result = new SuggesionResultSingle();
SimpleOrderedMap facets = (SimpleOrderedMap) ((SimpleOrderedMap) rsp.getValues().get("facet_counts"))
.get("facet_fields");
for (String field : fields) {
Iterator<Map.Entry> i = ((NamedList) facets.get(field)).iterator();
while (i.hasNext()) {
Map.Entry<String, NamedList<Object>> entry = i.next();
//analyze result for mapping
String s = " " + FieldAnalyzerService.analyzeString(core, df, entry.getKey());
//check if facet should be added
boolean add = true;
for (String qp : query.split(" ")) {
if (!s.toLowerCase().contains(" " + qp.toLowerCase()))
add = false;/*w w w .j ava 2s .c o m*/
}
if (add) {
Object o = entry.getValue();
result.addFacet(field, entry.getKey(), (Integer) o);
}
}
}
return result;
}
From source file:at.newmedialab.lmf.util.solr.suggestion.service.SuggestionService.java
License:Apache License
public void run(SolrQueryResponse rsp, String query, String df, String[] fields, String[] fqs, int limit, boolean multivalue) { //analyze query in advance query = FieldAnalyzerService.analyzeString(solrCore, df, query); SuggestionResult result = null;//w w w. j ava2s. c o m Object spellcheck_result = null; SolrQueryResponse response = query(query, df, fields, fqs); //of no results, try spellcheck (if defined and if spellchecked query differs from original) if (((ResultContext) response.getValues().get("response")).docs.size() > 0) { result = SuggestionResultFactory.createResult(solrCore, response, fields, query, df, multivalue); } else if (spellcheck_enabled) { String spellchecked_query = getSpellcheckedQuery(query, response); spellcheck_result = response.getValues().get("spellcheck"); //query with spellchecked query if (spellchecked_query != null) { response = query(spellchecked_query, df, fields, fqs); if (((ResultContext) response.getValues().get("response")).docs.size() > 0) { result = SuggestionResultFactory.createResult(solrCore, response, fields, spellchecked_query, df, multivalue); } } } //add result of spellcheck component if (spellcheck_result != null) { //TODO remove * on last position of collation rsp.add("spellcheck", spellcheck_result); } //create an empty result if (result == null) result = new SuggesionResultSingle(); rsp.add(SuggestionResultParams.SUGGESTIONS, result.write()); }
From source file:at.newmedialab.lmf.util.solr.suggestion.service.SuggestionService.java
License:Apache License
private String getSpellcheckedQuery(String query, SolrQueryResponse rsp) { try {//from w ww . j av a 2 s .c om if (((NamedList) ((NamedList) rsp.getValues().get("spellcheck")).get("suggestions")).size() > 0) { String s = (String) ((NamedList) ((NamedList) ((NamedList) rsp.getValues().get("spellcheck")) .get("suggestions"))).get("collation"); return s.substring(0, s.length() - 1); } } catch (NullPointerException e) { //TODO is this a nice solution? } return null; }
From source file:com.adr.bigdata.search.product.fe.BaseSuggestionHandler.java
@SuppressWarnings("rawtypes") @Override/*from w w w . jav a2s .c om*/ protected boolean zeroResult(SolrQueryResponse rsp) { Object suggestKeyword = rsp.getValues().get("listSuggestKeyword"); if (suggestKeyword == null) { return true; } else if (suggestKeyword instanceof NamedList) { if (((NamedList) suggestKeyword).size() == 0) { return true; } } return false; }
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 a2s .co 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:com.sn.solr.plugin.common.SolrHelper.java
License:Apache License
/** * Util method to extract the Facet response from Solr Query Response for a * given facet field. If not found returns null. * //from w w w . j a va2 s. c o m * @param res {@link SolrQueryResponse} * @param fieldName {@link String} field identifier string */ @SuppressWarnings("unchecked") public static NamedList<Number> getFacetsByField(SolrQueryResponse res, String fieldName) { NamedList<Number> list = null; try { NamedList<Object> respList = res.getValues(); if (respList != null) { NamedList<Object> fc = (NamedList<Object>) respList.get(FACET_CNT_TAG); if (fc != null) { NamedList<NamedList<Number>> ff = (NamedList<NamedList<Number>>) fc.get(FACET_FIELD_TAG); if (ff != null) { list = ff.get(fieldName); } } } } catch (Exception e) { e.printStackTrace(); } return list; }
From source file:com.sn.solr.plugin.common.SolrHelper.java
License:Apache License
/** * Constructs {@link SolrDocumentList} from the current {@link SolrQueryRequest} * and {@link SolrQueryResponse}./* w w w . java 2 s . c om*/ * * @param req {@link SolrQueryRequest} * @param res {@link SolrQueryResponse} * @return * @throws CorruptIndexException * @throws IOException */ public static SolrDocumentList getSolrDocList(SolrQueryRequest req, SolrQueryResponse res) throws CorruptIndexException, IOException { DocSlice slice = (DocSlice) res.getValues().get(RESP_EL_TAG); Set<String> returnFields = SolrHelper.getReturnFields(req); SolrDocumentList docList = new SolrDocumentList(); for (DocIterator it = slice.iterator(); it.hasNext();) { int docId = it.nextDoc(); Document doc = req.getSearcher().getReader().document(docId); SolrDocument sdoc = new SolrDocument(); for (Fieldable f : doc.getFields()) { String fn = f.name(); if (returnFields.contains(fn)) { sdoc.addField(fn, doc.get(fn)); } } docList.add(sdoc); } docList.setMaxScore(slice.maxScore()); docList.setNumFound(slice.matches()); docList.setStart(slice.offset()); return docList; }
From source file:com.sn.solr.utils.common.SolrHelper.java
License:Apache License
/** * Constructs {@link SolrDocumentList} from the current {@link SolrQueryRequest} * and {@link SolrQueryResponse}./*from w w w. j a va 2 s . c o m*/ * * @param req {@link SolrQueryRequest} * @param res {@link SolrQueryResponse} * @return * @throws CorruptIndexException * @throws IOException */ public static SolrDocumentList getSolrDocList(SolrQueryRequest req, SolrQueryResponse res) throws CorruptIndexException, IOException { DocSlice slice = (DocSlice) res.getValues().get(RESP_EL_TAG); Set<String> returnFields = SolrHelper.getReturnFields(req); SolrDocumentList docList = new SolrDocumentList(); for (DocIterator it = slice.iterator(); it.hasNext();) { int docId = it.nextDoc(); Document doc = req.getSearcher().getReader().document(docId); SolrDocument sdoc = new SolrDocument(); for (Fieldable f : doc.getFields()) { String fn = f.name(); if (returnFields.contains(fn)) { sdoc.addField(fn, doc.get(fn)); } } docList.add(sdoc); } docList.setMaxScore(slice.maxScore()); docList.setNumFound(slice.matches()); return docList; }