List of usage examples for org.apache.solr.client.solrj SolrQuery setSort
public SolrQuery setSort(String field, ORDER order)
From source file:com.doculibre.constellio.stats.StatsSearcher.java
License:Open Source License
public QueryResponse getMostClickedDocsForQuery(String collectionName, String query, SolrServer server, int start, int row) throws SolrServerException { String escapedQuery = StatsCompiler.escape(query); SolrQuery solrQuery = new SolrQuery(); solrQuery.setStart(start);// w w w . j a v a 2 s .com solrQuery.setRows(row); solrQuery.setSort("nbclick", SolrQuery.ORDER.desc); StringBuffer querySB = new StringBuffer( "collectionName:" + collectionName + " query:\"" + escapedQuery + "\""); solrQuery.setQuery(querySB.toString()); return server.query(solrQuery); }
From source file:com.doculibre.constellio.stats.StatsSearcher.java
License:Open Source License
public QueryResponse getMostClickedQueriesForURL(String collectionName, String url, SolrServer server, int start, int row) throws SolrServerException { SolrQuery solrQuery = new SolrQuery(); solrQuery.setStart(start);// w ww .jav a2 s. c o m solrQuery.setRows(row); solrQuery.setSort("nbclick", SolrQuery.ORDER.desc); StringBuffer querySB = new StringBuffer("collectionName:" + collectionName + " url:\"" + url + "\""); solrQuery.setQuery(querySB.toString()); return server.query(solrQuery); }
From source file:com.github.fengtan.sophie.tables.DocumentsTable.java
License:Open Source License
/** * Get document to display at a specific row index. The document is * retrieved from the cache. If it is not in the cache, then we fetch a new * page of results and we populate the cache. * /* ww w . java 2 s.com*/ * @param rowIndex * Row index. * @return Solr document. * @throws SophieException * If the document could not be fetched from Solr. */ private SolrDocument getRemoteDocument(int rowIndex) throws SophieException { // Compute page ID. int page = rowIndex / PAGE_SIZE; // If page is not in the cache, then fetch it from Solr and populate the // cache. if (!pages.containsKey(page)) { SolrQuery query = getBaseQuery(page * PAGE_SIZE, PAGE_SIZE); query.setSort(sortField, sortOrder); try { pages.put(page, Sophie.client.query(query).getResults()); } catch (SolrServerException | IOException | SolrException e) { throw new SophieException("Unable to fetch remote document " + rowIndex, e); } } // Return Solr document from the cache. return pages.get(page).get(rowIndex % PAGE_SIZE); }
From source file:com.idealista.solrmeter.model.service.impl.QueryServiceSolrJImpl.java
License:Apache License
protected SolrQuery createQuery(String q, String fq, String qt, boolean highlight, String facetFields, String sort, String sortOrder, Integer rows, Integer start, String otherParams) throws QueryException { SolrQuery query = new SolrQuery(); if (q != null) { query.setQuery(q);//ww w . j a v a 2s .c o m } if (fq != null) { List<String> filterQueries = this.getFilterQueries(fq); for (String filterQuery : filterQueries) { query.addFilterQuery(filterQuery); } } query.setHighlight(highlight); if (facetFields == null || "".equals(facetFields)) { query.setFacet(false); } else { query.setFacet(true); List<String> facets = this.getFacets(facetFields); for (String facet : facets) { query.addFacetField(facet); } } if (sort != null && !"".equals(sort)) { query.setSort(sort, ORDER.valueOf(sortOrder)); } if (rows != null && rows < 0) { throw new QueryException("Rows can't be less than 0"); } else if (rows != null) { query.setRows(rows); } if (start != null && start < 0) { throw new QueryException("Rows can't be less than 0"); } else if (start != null) { query.setStart(start); } if (otherParams != null) { List<String> params = this.getOtherParams(otherParams); for (String param : params) { query.add(getParamName(param), getParamValue(param)); } } return query; }
From source file:com.ifactory.press.db.solr.processor.UpdateDocValuesTest.java
License:Apache License
private void assertDocValues(int n) throws SolrServerException { SolrQuery query = new SolrQuery("*:*"); query.setSort(WEIGHT_DV, ORDER.desc); assertEquals(uri(1), getFirstUri(query)); query.setSort(WEIGHT_DV, ORDER.asc); assertEquals(uri(n), getFirstUri(query)); }
From source file:com.ifactory.press.db.solr.processor.UpdateDocValuesTest.java
License:Apache License
private void assertNoDocValues() throws SolrServerException { SolrQuery query = new SolrQuery("*:*"); String firstUri = getFirstUri(query); // with no doc values, should get the same doc first: query.setSort(WEIGHT_DV, ORDER.desc); assertEquals(firstUri, getFirstUri(query)); // no matter what the order is query.setSort(WEIGHT_DV, ORDER.asc); assertEquals(firstUri, getFirstUri(query)); }
From source file:cz.incad.vdk.client.tools.Search.java
License:Open Source License
public String getAsXML() throws JSONException { try {/*from w ww . j a v a 2 s . c o m*/ String q = req.getParameter("q"); SolrQuery query = new SolrQuery(); if (q == null || q.equals("")) { q = "*:*"; query.setSort("_version_", SolrQuery.ORDER.desc); } query.setQuery(q); query.set("q.op", "AND"); query.setFacet(true); query.setStart(getStart()); query.setRows(getRows()); if (LoggedController.isLogged(req)) { query.addFacetField(opts.getStrings("user_facets")); } query.addFacetField(opts.getStrings("facets")); query.setFacetMinCount(1); JSONObject others = opts.getJSONObject("otherParams"); Iterator keys = others.keys(); while (keys.hasNext()) { String key = (String) keys.next(); Object val = others.get(key); if (val instanceof Integer) { query.set(key, (Integer) val); } else if (val instanceof String) { query.set(key, (String) val); } else if (val instanceof Boolean) { query.set(key, (Boolean) val); } } addFilters(query); return IndexerQuery.xml(query); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); return null; } }
From source file:de.fatalix.bookery.bl.solr.SolrHandler.java
License:Open Source License
public QueryResponse searchSolrIndexSorted(String queryString, String fields, int rows, int startOffset, String sortField) throws SolrServerException { SolrServer solr = null;/*w w w . j a v a2 s. c om*/ try { solr = bookeryService.getSolrConnection(); } catch (IOException ex) { throw new SolrServerException(ex.getMessage()); } SolrQuery query = new SolrQuery(); query.setQuery(queryString); query.setRows(rows); query.setStart(startOffset); query.setSort(sortField, SolrQuery.ORDER.desc); query.setFields(fields); QueryResponse rsp = solr.query(query); return rsp; }
From source file:edu.harvard.lib.lcloud.ItemDAO.java
License:Open Source License
/** * Returns a SolrDocumentList for a given set of search parameters. Search parameters are parsed * and mapped into solr (solrj) query syntax, and solr query is performed. * @param queryParams query parameters to map to a solr query * @return the SolrDocumentList for this query * @see SolrDocumentList//from w w w. j a v a 2s .c o m */ private SolrDocumentList doQuery(MultivaluedMap<String, String> queryParams) { SolrDocumentList docs = null; HttpSolrServer server = null; ArrayList<String> queryList = new ArrayList<String>(); server = SolrServer.getSolrConnection(); SolrQuery query = new SolrQuery(); for (String key : queryParams.keySet()) { String value = queryParams.getFirst(key); System.out.println(key + " : " + queryParams.getFirst(key) + "\n"); if (key.equals("start")) { int startNo = Integer.parseInt(value); if (startNo < 0) startNo = 0; query.setStart(startNo); } else if (key.equals("limit")) { limit = Integer.parseInt(value); query.setRows(limit); } else if (key.equals("sort.asc") || key.equals("sort")) query.setSort(value, ORDER.asc); else if (key.equals("sort.desc")) query.setSort(value, ORDER.desc); else if (key.startsWith("facet")) { query.setFacet(true); String[] facetArray = value.split(","); for (String f : facetArray) { query.addFacetField(f); } } else { if (key.endsWith("_exact")) queryList.add(key.replace("_exact", "") + ":\"" + value + "\""); else { if (value.contains(" ")) value = "( " + value.replaceAll(" ", " AND ") + ")"; if (key.equals("q")) queryList.add("keyword:" + value); else queryList.add(key + "_keyword:" + value); } } } Iterator<String> it = queryList.iterator(); String queryStr = ""; while (it.hasNext()) { String qTerm = (String) it.next(); System.out.print("QT: " + qTerm + "\n"); queryStr += qTerm; System.out.print("QS: " + queryStr + "\n"); if (it.hasNext()) queryStr += " AND "; } System.out.print("queryStr: " + queryStr); query.setQuery(queryStr); QueryResponse response = null; try { response = server.query(query); } catch (SolrServerException se) { log.error(se.getMessage()); throw new BadParameterException(se.getMessage()); } catch (RemoteSolrException rse) { if (rse.getMessage().contains("SyntaxError")) { log.error("solr syntax error"); throw new BadParameterException("Incorrect query syntax"); } else { String msg = rse.getMessage().replace("_keyword", ""); log.error(msg); throw new BadParameterException("Incorrect query syntax:" + msg); } } List<FacetField> facets = response.getFacetFields(); facet = null; if (facets != null) { facet = new Facet(); List<FacetType> facetTypes = new ArrayList<FacetType>(); for (FacetField facetField : facets) { List<FacetTerm> facetTerms = new ArrayList<FacetTerm>(); FacetType facetType = new FacetType(); facetType.setFacetName(facetField.getName()); List<FacetField.Count> facetEntries = facetField.getValues(); for (FacetField.Count fcount : facetEntries) { if (fcount.getCount() > 0) { FacetTerm facetTerm = new FacetTerm(); facetTerm.setTermName(fcount.getName()); facetTerm.setTermCount(fcount.getCount()); //System.out.println(fcount.getName() + ": " + fcount.getCount()); facetTerms.add(facetTerm); } } facetType.setFacetTerms(facetTerms); facetTypes.add(facetType); } facet.setFacetTypes(facetTypes); } docs = response.getResults(); return docs; }
From source file:edu.unc.lib.dl.ui.service.SolrQueryLayerService.java
License:Apache License
/** * Retrieves a list of the nearest windowSize neighbors within the nearest parent collection or folder around the * item metadata, based on the order field of the item. The first windowSize - 1 neighbors are retrieved to each side * of the item, and trimmed so that there are always windowSize - 1 neighbors surrounding the item if possible. If no * order field is available, a list of arbitrary windowSize neighbors is returned. * // w w w. j a v a2s . co m * @param metadata * Record which the window pivots around. * @param windowSize * max number of items in the window. This includes the pivot, so odd numbers are recommended. * @param accessGroups * Access groups of the user making this request. * @return */ public List<BriefObjectMetadataBean> getNeighboringItems(BriefObjectMetadataBean metadata, int windowSize, AccessGroupSet accessGroups) { // Get the common access restriction clause (starts with "AND ...") StringBuilder accessRestrictionClause = new StringBuilder(); try { addAccessRestrictions(accessRestrictionClause, accessGroups); } catch (AccessRestrictionException e) { // If the user doesn't have any access groups, they don't have access to anything, return null. LOG.error(e.getMessage()); return null; } // Prepare the common query object, including a filter for resource type and the // facet which selects only the item's siblings. SolrQuery solrQuery = new SolrQuery(); solrQuery.setFacet(true); solrQuery.addFilterQuery(solrSettings.getFieldName(SearchFieldKeys.RESOURCE_TYPE.name()) + ":File " + solrSettings.getFieldName(SearchFieldKeys.RESOURCE_TYPE.name()) + ":Aggregate"); CutoffFacet ancestorPath = null; if (metadata.getResourceType().equals(searchSettings.resourceTypeFile) || metadata.getResourceType().equals(searchSettings.resourceTypeAggregate)) { ancestorPath = metadata.getAncestorPathFacet(); } else { ancestorPath = metadata.getPath(); } if (ancestorPath != null) { // We want only objects at the same level of the hierarchy ancestorPath.setCutoff(ancestorPath.getHighestTier() + 1); facetFieldUtil.addToSolrQuery(ancestorPath, solrQuery); } // If this item has no display order, get arbitrary items surrounding it. Long pivotOrder = metadata.getDisplayOrder(); if (pivotOrder == null) { LOG.debug("No display order, just querying for " + windowSize + " siblings"); StringBuilder query = new StringBuilder(); List<BriefObjectMetadataBean> list = null; query.append("*:*"); query.append(accessRestrictionClause); solrQuery.setQuery(query.toString()); solrQuery.setStart(0); solrQuery.setRows(windowSize); solrQuery.setSort(solrSettings.getFieldName(SearchFieldKeys.DISPLAY_ORDER.name()), SolrQuery.ORDER.desc); try { QueryResponse queryResponse = this.executeQuery(solrQuery); list = queryResponse.getBeans(BriefObjectMetadataBean.class); } catch (SolrServerException e) { LOG.error("Error retrieving Neighboring items: " + e); return null; } return list; // Otherwise, query for items surrounding this item. } else { LOG.debug("Display order is " + pivotOrder); // Find the right and left lists StringBuilder query; List<BriefObjectMetadataBean> leftList = null; List<BriefObjectMetadataBean> rightList = null; solrQuery.setStart(0); solrQuery.setRows(windowSize - 1); // Right list query = new StringBuilder(); query.append(solrSettings.getFieldName(SearchFieldKeys.DISPLAY_ORDER.name())).append(":[") .append(pivotOrder + 1).append(" TO *]"); query.append(accessRestrictionClause); solrQuery.setQuery(query.toString()); solrQuery.setSort(solrSettings.getFieldName(SearchFieldKeys.DISPLAY_ORDER.name()), SolrQuery.ORDER.asc); try { QueryResponse queryResponse = this.executeQuery(solrQuery); rightList = queryResponse.getBeans(BriefObjectMetadataBean.class); } catch (SolrServerException e) { LOG.error("Error retrieving Neighboring items: " + e); return null; } LOG.debug("Got " + rightList.size() + " items for right list"); // Left list // (Note that display order stuff is reversed.) query = new StringBuilder(); query.append(solrSettings.getFieldName(SearchFieldKeys.DISPLAY_ORDER.name())).append(":[* TO ") .append(pivotOrder - 1).append("]"); query.append(accessRestrictionClause); solrQuery.setQuery(query.toString()); solrQuery.setSort(solrSettings.getFieldName(SearchFieldKeys.DISPLAY_ORDER.name()), SolrQuery.ORDER.desc); try { QueryResponse queryResponse = this.executeQuery(solrQuery); leftList = queryResponse.getBeans(BriefObjectMetadataBean.class); } catch (SolrServerException e) { LOG.error("Error retrieving Neighboring items: " + e); return null; } LOG.debug("Got " + leftList.size() + " items for left list"); // Trim the lists int halfWindow = windowSize / 2; // If we have enough in both lists, trim both to be // halfWindow long. if (leftList.size() >= halfWindow && rightList.size() >= halfWindow) { LOG.debug("Trimming both lists"); leftList.subList(halfWindow, leftList.size()).clear(); rightList.subList(halfWindow, rightList.size()).clear(); // If we don't have enough in the left list and we have extra in the right list, // try to pick up the slack by trimming fewer items from the right list. } else if (leftList.size() < halfWindow && rightList.size() > halfWindow) { LOG.debug("Picking up slack from right list"); // How much extra do we need from the right list? int extra = halfWindow - leftList.size(); // Only "take" the extra (ie, clear less of the right list) if we have it available. if (halfWindow + extra < rightList.size()) rightList.subList(halfWindow + extra, rightList.size()).clear(); } else if (rightList.size() < halfWindow && leftList.size() > halfWindow) { LOG.debug("Picking up slack from left list"); int extra = halfWindow - rightList.size(); if (halfWindow + extra < leftList.size()) leftList.subList(halfWindow + extra, leftList.size()).clear(); } // (Otherwise, we do no trimming, since both lists are smaller or the same size // as the window.) // Assemble the result. Collections.reverse(leftList); leftList.add(metadata); leftList.addAll(rightList); return leftList; } }