List of usage examples for org.apache.solr.common.params CommonParams SORT
String SORT
To view the source code for org.apache.solr.common.params CommonParams SORT.
Click Source Link
From source file:com.browseengine.bobo.servlet.BrowseServlet.java
License:Open Source License
@Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { SolrParams params = new BoboHttpRequestParam(req); String qstring = params.get(CommonParams.Q); String df = params.get(CommonParams.DF); String sortString = params.get(CommonParams.SORT); BoboDefaultQueryBuilder qbuilder = new BoboDefaultQueryBuilder(); Query query = qbuilder.parseQuery(qstring, df); Sort sort = qbuilder.parseSort(sortString); BrowseRequest br = null;/*from w w w . ja va2 s .com*/ try { br = BoboRequestBuilder.buildRequest(params, query, sort); BrowseResult result = _svc.browse(br); res.setCharacterEncoding("UTF-8"); Writer writer = res.getWriter(); try { String val = BrowseJSONSerializer.serialize(result); writer.write(val); } catch (JSONException je) { throw new IOException(je.getMessage()); } } catch (BrowseException e) { throw new ServletException(e.getMessage(), e); } }
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/*from w w w. j a va 2 s . c o 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 ---- > * /*from ww w . j a v 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) {/*w w w. j a 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.sn.solr.plugin.comp.RankComponent.java
License:Apache License
private static SolrQuery.ORDER getRankFieldSortOrder(SolrParams params, String rankField) { SolrQuery.ORDER rankFieldSort = FIELD_RANK_SORT; if (params.get(CommonParams.SORT, rankField + " asc").contains(rankField + " desc")) { rankFieldSort = SolrQuery.ORDER.desc; }//from w w w .ja v a 2 s . c o m return rankFieldSort; }
From source file:com.tsgrp.solr.handler.NYPhilSearchHandler.java
License:Mozilla Public License
/** * @see org.apache.solr.handler.component.SearchHandler#handleRequestBody(org.apache.solr.request.SolrQueryRequest, * org.apache.solr.request.SolrQueryResponse) *//*from ww w.jav a2 s . co m*/ @Override public void handleRequestBody(SolrQueryRequest req, SolrQueryResponse rsp) throws Exception, ParseException, InstantiationException, IllegalAccessException { SolrParams requestParams = req.getParams(); NamedList<Object> params = requestParams.toNamedList(); //for now lets echo the handler and all the params for debugging purposes //params.add( CommonParams.HEADER_ECHO_HANDLER, Boolean.TRUE ); //params.add( CommonParams.HEADER_ECHO_PARAMS, CommonParams.EchoParamStyle.ALL ); String rows = (String) params.get(CommonParams.ROWS); if (rows == null || rows.trim().length() < 1) { //setup items per page, default to 10 items params.add(CommonParams.ROWS, 10); rows = "10"; } //enable faceting and only return facets with at least 1 item params.add(FacetParams.FACET, Boolean.TRUE); params.add(FacetParams.FACET_MINCOUNT, 1); //defult ordering to index order (alphabetical) params.add(FacetParams.FACET_SORT, FacetParams.FACET_SORT_INDEX); //only return a maximum of 10 facet values params.add(FacetParams.FACET_LIMIT, 10); //always add facets unless they are explicitly not requested String addFacets = (String) params.get(PARAM_GENERATE_FACETS); boolean generateFacets = (addFacets == null) ? true : addFacets.equalsIgnoreCase("true"); //enable highlighting params.add(HighlightParams.HIGHLIGHT, Boolean.TRUE); //remove the query if provided, always want to use our translated query String originalQuery = (String) params.remove(CommonParams.Q); if (logger.isDebugEnabled()) { logger.debug("Original query: " + originalQuery); } //setup sorting params String sortColumn = (String) params.get(PARAM_SORT_COLUMN); String sortOrder = (String) params.get(PARAM_SORT_ORDER); if (sortColumn != null && sortOrder != null) { params.add(CommonParams.SORT, sortColumn + " " + sortOrder); } //get date fields String sDateFrom = (String) params.get(PARAM_DATE_FROM); String sDateTo = (String) params.get(PARAM_DATE_TO); Date dateFrom = null; Date dateTo = null; if (sDateFrom != null && sDateTo != null) { dateFrom = DATE_FORMAT_PARAM.parse(sDateFrom); dateTo = DATE_FORMAT_PARAM.parse(sDateTo); } String keywords = (String) params.get(PARAM_KEYWORDS); if (keywords == null || keywords.trim().length() < 1) { //query everything since nothing was provided keywords = "*"; } //always use the extended dismax parser params.add("defType", ExtendedDismaxQParserPlugin.NAME); //the keywords sent in are the query since we're in DISMAX mode params.add(CommonParams.Q, keywords); String pageIndex = (String) params.get(PARAM_PAGE_INDEX); String resultsPerPage = (String) params.get(PARAM_RESULTS_PER_PAGE); if (resultsPerPage == null || resultsPerPage.trim().length() < 0) { resultsPerPage = "10"; } if (pageIndex == null || pageIndex.trim().length() < 1) { pageIndex = "1"; } //figure out the skip count, use the (pageIndex - 1) * resultsPerPage //ie pageIndex = 3, 10 results per page, we'll set start to (3-1)*10 = 20 int start = (Integer.parseInt(pageIndex) - 1) * Integer.parseInt(resultsPerPage); params.add(CommonParams.START, start); String doctype = (String) params.get(PARAM_DOCTYPE); if (doctype == null || doctype.trim().length() < 1) { doctype = ""; } String facetQuery = (String) params.get(PARAM_FACET_QUERY); if (facetQuery != null && facetQuery.trim().length() > 0) { //facetQuery is pre formatted and correct, just add it as a filter query params.add(CommonParams.FQ, facetQuery); } String suggestedQuery = (String) params.get(PARAM_SUGGESTED_QUERY); if (suggestedQuery != null && suggestedQuery.trim().length() > 0) { //suggestedQuery is pre formatted and correct, just add it as a filter query params.add(CommonParams.FQ, suggestedQuery); } //base fields params.add(DisMaxParams.QF, "nyp:DocumentType"); params.add(DisMaxParams.QF, "nyp:Notes"); //program fields params.add(DisMaxParams.QF, "npp:ProgramID"); params.add(DisMaxParams.QF, "npp:Season"); params.add(DisMaxParams.QF, "npp:OrchestraCode"); params.add(DisMaxParams.QF, "npp:OrchestraName"); params.add(DisMaxParams.QF, "npp:LocationName"); params.add(DisMaxParams.QF, "npp:VenueName"); params.add(DisMaxParams.QF, "npp:EventTypeName"); params.add(DisMaxParams.QF, "npp:SubEventName"); params.add(DisMaxParams.QF, "npp:ConductorName"); params.add(DisMaxParams.QF, "npp:SoloistsNames"); params.add(DisMaxParams.QF, "npp:SoloistsInstrumentName"); params.add(DisMaxParams.QF, "npp:WorksComposerNames"); params.add(DisMaxParams.QF, "npp:WorksTitle"); params.add(DisMaxParams.QF, "npp:WorksShortTitle"); params.add(DisMaxParams.QF, "npp:WorksConductorNames"); //printedMusic fields params.add(DisMaxParams.QF, "npm:LibraryID"); params.add(DisMaxParams.QF, "npm:ShortTitle"); params.add(DisMaxParams.QF, "npm:ComposerName"); params.add(DisMaxParams.QF, "npm:PublisherName"); params.add(DisMaxParams.QF, "npm:ComposerNameTitle"); params.add(DisMaxParams.QF, "npm:ScoreMarkingArtist"); params.add(DisMaxParams.QF, "npm:ScoreEditionTypeDesc"); params.add(DisMaxParams.QF, "npm:ScoreNotes"); //part fields params.add(DisMaxParams.QF, "npm:PartTypeDesc"); params.add(DisMaxParams.QF, "npm:PartMarkingArtist"); params.add(DisMaxParams.QF, "npm:UsedByArtistName"); //businessRecord fields params.add(DisMaxParams.QF, "npb:BoxNumber"); params.add(DisMaxParams.QF, "npb:RecordGroup"); params.add(DisMaxParams.QF, "npb:Series"); params.add(DisMaxParams.QF, "npb:SubSeries"); params.add(DisMaxParams.QF, "npb:Folder"); params.add(DisMaxParams.QF, "npb:Names"); params.add(DisMaxParams.QF, "npb:Subject"); params.add(DisMaxParams.QF, "npb:Abstract"); //visual fields params.add(DisMaxParams.QF, "npv:ID"); params.add(DisMaxParams.QF, "npv:BoxNumber"); params.add(DisMaxParams.QF, "npv:PhilharmonicSource"); params.add(DisMaxParams.QF, "npv:OutsideSource"); params.add(DisMaxParams.QF, "npv:Photographer"); params.add(DisMaxParams.QF, "npv:CopyrightHolder"); params.add(DisMaxParams.QF, "npv:PlaceOfImage"); params.add(DisMaxParams.QF, "npv:PersonalNames"); params.add(DisMaxParams.QF, "npv:CorporateNames"); params.add(DisMaxParams.QF, "npv:Event"); params.add(DisMaxParams.QF, "npv:ImageType"); params.add(DisMaxParams.QF, "npv:LocationName"); params.add(DisMaxParams.QF, "npv:VenueName"); //audio fields params.add(DisMaxParams.QF, "npa:ProgramID"); params.add(DisMaxParams.QF, "npa:Location"); params.add(DisMaxParams.QF, "npa:EventTypeName"); params.add(DisMaxParams.QF, "npa:ConductorName"); params.add(DisMaxParams.QF, "npa:SoloistsAndInstruments"); params.add(DisMaxParams.QF, "npa:ComposerWork"); params.add(DisMaxParams.QF, "npa:OrchestraName"); params.add(DisMaxParams.QF, "npa:IntermissionFeature"); params.add(DisMaxParams.QF, "npa:LocationName"); params.add(DisMaxParams.QF, "npa:VenueName"); params.add(DisMaxParams.QF, "npa:SubEventName"); params.add(DisMaxParams.QF, "npa:URLLocation"); params.add(DisMaxParams.QF, "npa:IntermissionGuests"); params.add(DisMaxParams.QF, "npa:Announcer"); //video fields params.add(DisMaxParams.QF, "npx:ProgramID"); params.add(DisMaxParams.QF, "npx:Location"); params.add(DisMaxParams.QF, "npx:EventTypeName"); params.add(DisMaxParams.QF, "npx:ConductorName"); params.add(DisMaxParams.QF, "npx:SoloistsAndInstruments"); params.add(DisMaxParams.QF, "npx:ComposerNameWork"); params.add(DisMaxParams.QF, "npx:OrchestraName"); params.add(DisMaxParams.QF, "npx:IntermissionFeature"); params.add(DisMaxParams.QF, "npx:LocationName"); params.add(DisMaxParams.QF, "npx:VenueName"); params.add(DisMaxParams.QF, "npx:SubEventName"); params.add(DisMaxParams.QF, "npx:IntermissionGuests"); params.add(DisMaxParams.QF, "npx:Announcer"); params.add(DisMaxParams.QF, "npt:tagged"); //add in all the restrictions that can be applied to a document type count in the same filter query //this includes all DATE range queries //if a date query does not exist, the TYPE is queried so all results are shown //restriction is applied to business records so only the web publishable items are shown StringBuffer filterTypesCountsQuery = new StringBuffer(); if (dateFrom != null && dateTo != null) { //program date query filterTypesCountsQuery.append("(npp\\:Date:[" + solrField.toExternal(dateFrom) + " TO " + solrField.toExternal(dateTo) + "])"); //printedMusic (scores) and parts have no date range, so just or in the type so those results come back filterTypesCountsQuery.append(" OR (nyp\\:DocumentType:Printed Music)"); filterTypesCountsQuery.append(" OR (nyp\\:DocumentType:Part)"); //business record range AND web publishable restriction filterTypesCountsQuery .append(" OR (nyp\\:WebPublishable:true AND ((npb\\:DateFrom:[" + solrField.toExternal(dateFrom) + " TO *] AND npb\\:DateTo:[* TO " + solrField.toExternal(dateTo) + "])"); filterTypesCountsQuery.append(" OR (npb\\:DateFrom:[* TO " + solrField.toExternal(dateFrom) + "] AND npb\\:DateTo:[* TO " + solrField.toExternal(dateTo) + "] AND npb\\:DateTo:[" + solrField.toExternal(dateFrom) + " TO *])"); filterTypesCountsQuery.append(" OR (npb\\:DateFrom:[" + solrField.toExternal(dateFrom) + " TO *] AND npb\\:DateTo:[" + solrField.toExternal(dateTo) + " TO *] AND npb\\:DateFrom:[* TO " + solrField.toExternal(dateFrom) + "])))"); //visual filterTypesCountsQuery.append(" OR ((npv\\:DateFrom:[" + solrField.toExternal(dateFrom) + " TO *] AND npv\\:DateTo:[* TO " + solrField.toExternal(dateTo) + "])"); filterTypesCountsQuery.append(" OR (npv\\:DateFrom:[* TO " + solrField.toExternal(dateFrom) + "] AND npv\\:DateTo:[* TO " + solrField.toExternal(dateTo) + "] AND npv\\:DateTo:[" + solrField.toExternal(dateFrom) + " TO *])"); filterTypesCountsQuery.append(" OR (npv\\:DateFrom:[" + solrField.toExternal(dateFrom) + " TO *] AND npv\\:DateTo:[" + solrField.toExternal(dateTo) + " TO *] AND npv\\:DateFrom:[* TO " + solrField.toExternal(dateFrom) + "]))"); //audio filterTypesCountsQuery.append(" OR (npa\\:Date:[" + solrField.toExternal(dateFrom) + " TO " + solrField.toExternal(dateTo) + "])"); //video filterTypesCountsQuery.append(" OR (npx\\:Date:[" + solrField.toExternal(dateFrom) + " TO " + solrField.toExternal(dateTo) + "])"); } else { //no date queries, just perform query based on type restrictions filterTypesCountsQuery.append( "(nyp\\:DocumentType:Program) OR (nyp\\:DocumentType:Printed Music) OR (nyp\\:DocumentType:Part) OR (nyp\\:DocumentType:Business Record AND nyp\\:WebPublishable:true)"); filterTypesCountsQuery.append( " OR (nyp\\:DocumentType:Visual) OR (nyp\\:DocumentType:Audio) OR (nyp\\:DocumentType:Video)"); } params.add(CommonParams.FQ, filterTypesCountsQuery); //default facet for document type that will always return the counts regardless of filter queries applied params.add(FacetParams.FACET_FIELD, "{!ex=test}nyp:DocumentType_facet"); //allow this facet to always display all values, even when there are 0 results for the type params.add("f.nyp:DocumentType_facet.facet.mincount", 0); if (doctype.equalsIgnoreCase("program")) { //set the document type restriction params.add(CommonParams.FQ, "{!tag=test}nyp\\:DocumentType:Program"); if (generateFacets) { params.add(FacetParams.FACET_FIELD, "npp:ConductorName_facet"); params.add(FacetParams.FACET_FIELD, "npp:SoloistsNames_facet"); params.add(FacetParams.FACET_FIELD, "npp:WorksComposerNames_facet"); params.add(FacetParams.FACET_FIELD, "npp:LocationName_facet"); params.add(FacetParams.FACET_FIELD, "npp:VenueName_facet"); params.add(FacetParams.FACET_FIELD, "npp:EventTypeName_facet"); params.add(FacetParams.FACET_FIELD, "npp:Season_facet"); } } else if (doctype.equalsIgnoreCase("printedMusic")) { //set the document type restriction params.add(CommonParams.FQ, "{!tag=test}nyp\\:DocumentType:Printed Music"); if (generateFacets) { params.add(FacetParams.FACET_FIELD, "npm:ScoreMarkingArtist_facet"); params.add(FacetParams.FACET_FIELD, "npm:ComposerName_facet"); } } else if (doctype.equalsIgnoreCase("part")) { //set the document type restriction params.add(CommonParams.FQ, "{!tag=test}nyp\\:DocumentType:Part"); if (generateFacets) { params.add(FacetParams.FACET_FIELD, "npm:ComposerName_facet"); params.add(FacetParams.FACET_FIELD, "npm:UsedByArtistName_facet"); params.add(FacetParams.FACET_FIELD, "npm:PartMarkingArtist_facet"); params.add(FacetParams.FACET_FIELD, "npm:PartTypeDesc_facet"); } // if sort parameter has been supplied (e.g. non-facet search) - apply additional part sorting if (sortColumn != null && sortOrder != null) { logger.debug("Addition additional sort parameter for PART type..."); String prevParams = (String) params.get(CommonParams.SORT); String newParams = prevParams + ", npm:PartID ASC"; params.add(CommonParams.SORT, newParams); } } else if (doctype.equalsIgnoreCase("businessRecord")) { //set the document type restriction params.add(CommonParams.FQ, "{!tag=test}nyp\\:DocumentType:Business Record"); if (generateFacets) { params.add(FacetParams.FACET_FIELD, "npb:Names_facet"); params.add(FacetParams.FACET_FIELD, "npb:Subject_facet"); params.add(FacetParams.FACET_FIELD, "npb:RecordGroup_facet"); params.add(FacetParams.FACET_FIELD, "npb:Series_facet"); params.add(FacetParams.FACET_FIELD, "npb:SubSeries_facet"); } } else if (doctype.equalsIgnoreCase("visual")) { //set the document type restriction params.add(CommonParams.FQ, "{!tag=test}nyp\\:DocumentType:Visual"); if (generateFacets) { params.add(FacetParams.FACET_FIELD, "npv:Photographer_facet"); params.add(FacetParams.FACET_FIELD, "npv:CopyrightHolder_facet"); params.add(FacetParams.FACET_FIELD, "npv:ImageType_facet"); params.add(FacetParams.FACET_FIELD, "npv:PlaceOfImage_facet"); params.add(FacetParams.FACET_FIELD, "npv:Event_facet"); params.add(FacetParams.FACET_FIELD, "npv:PersonalNames_facet"); params.add(FacetParams.FACET_FIELD, "npv:LocationName_facet"); params.add(FacetParams.FACET_FIELD, "npv:VenueName_facet"); } } else if (doctype.equalsIgnoreCase("audio")) { //set the document type restriction params.add(CommonParams.FQ, "{!tag=test}nyp\\:DocumentType:Audio"); //no facets being generated } else if (doctype.equalsIgnoreCase("video")) { //set the document type restriction params.add(CommonParams.FQ, "{!tag=test}nyp\\:DocumentType:Video"); //no facets being generated } else { logger.error("Invalid document type: " + doctype); throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Invalid document type: " + doctype); } if (logger.isDebugEnabled()) { logger.debug("Params: " + params); } //set the new request parameters, then call the default handler behavior req.setParams(SolrParams.toSolrParams(params)); super.handleRequestBody(req, rsp); }
From source file:de.cosmocode.solr.SolrJQuery.java
License:Apache License
@Override public void sortFields(String... sortFields) { solrJQuery.remove(CommonParams.SORT); for (String field : sortFields) { solrJQuery.addSortField(field, ORDER.desc); }//w ww . j a va 2 s . c om }
From source file:edu.toronto.cs.cidb.solr.SolrScriptService.java
License:Open Source License
/** * Perform a search, falling back on the suggested spellchecked query if the original query fails to return any * results./*w ww . j ava 2 s . c om*/ * * @param params the Solr parameters to use, should contain at least a value for the "q" parameter; use * {@link #getSolrQuery(String, int, int)} to get the proper parameter expected by this method * @return the list of matching documents, empty if there are no matching terms */ private SolrDocumentList search(MapSolrParams params) { try { QueryResponse response = this.server.query(params); SolrDocumentList results = response.getResults(); if (results.size() == 0 && !response.getSpellCheckResponse().isCorrectlySpelled()) { String suggestedQuery = response.getSpellCheckResponse().getCollatedResult(); // The spellcheck doesn't preserve the identifiers, manually // correct this suggestedQuery = suggestedQuery.replaceAll("term_category:hip", "term_category:HP"); MapSolrParams newParams = new MapSolrParams( getSolrQuery(suggestedQuery, params.get(CommonParams.SORT), params.getInt(CommonParams.ROWS, -1), params.getInt(CommonParams.START, 0))); return this.server.query(newParams).getResults(); } else { return results; } } catch (SolrServerException ex) { this.logger.error("Failed to search: {}", ex.getMessage(), ex); } return null; }
From source file:edu.toronto.cs.cidb.solr.SolrScriptService.java
License:Open Source License
/** * Convert a Lucene query string into a map of Solr parameters. More specifically, places the input query under the * "q" parameter, and adds parameters for requesting a spellcheck result. * * @param query the lucene query string to use * @param sort the sort criteria ("fiel_name order') * @param rows the number of items to return, or -1 to use the default number of results * @param start the number of items to skip, i.e. the index of the first hit to return, 0-based * @return a map of Solr query parameter ready to be used for constructing a {@link MapSolrParams} object *//*www . j av a 2 s . co m*/ private Map<String, String> getSolrQuery(String query, String sort, int rows, int start) { Map<String, String> result = new HashMap<String, String>(); result.put(CommonParams.START, start + ""); if (rows > 0) { result.put(CommonParams.ROWS, rows + ""); } result.put(CommonParams.Q, query); if (!StringUtils.isBlank(sort)) { result.put(CommonParams.SORT, sort); } result.put("spellcheck", Boolean.toString(true)); result.put("spellcheck.collate", Boolean.toString(true)); result.put("spellcheck.onlyMorePopular", Boolean.toString(true)); return result; }
From source file:edu.toronto.cs.phenotips.solr.AbstractSolrScriptService.java
License:Open Source License
/** * Convert a Lucene query string into a map of Solr parameters. More specifically, places the input query under the * "q" parameter, and adds parameters for requesting a spellcheck result. * //from w w w . j a v a 2 s.c o m * @param query the lucene query string to use * @param sort the sort criteria ("fiel_name order') * @param rows the number of items to return, or -1 to use the default number of results * @param start the number of items to skip, i.e. the index of the first hit to return, 0-based * @return a map of Solr query parameter ready to be used for constructing a {@link MapSolrParams} object */ private Map<String, String> getSolrQuery(String query, String sort, int rows, int start) { Map<String, String> result = new HashMap<String, String>(); result.put(CommonParams.START, start + ""); if (rows > 0) { result.put(CommonParams.ROWS, rows + ""); } result.put(CommonParams.Q, query); if (StringUtils.isNotBlank(sort)) { result.put(CommonParams.SORT, sort); } result.put("spellcheck", Boolean.toString(true)); result.put("spellcheck.collate", Boolean.toString(true)); return result; }