List of usage examples for org.apache.solr.common SolrDocumentList getMaxScore
public Float getMaxScore()
From source file:br.ufrgs.inf.dsmoura.repository.controller.solr.SolrConversionUtil.java
public static List<AssetSolrDTO> fromSolrDocumentListToAsset(SolrDocumentList solrAssetDocs, Float maxScore) { List<AssetSolrDTO> assets = new ArrayList<AssetSolrDTO>(); for (SolrDocument d : solrAssetDocs) { AssetSolrDTO assetSolrDTO = new AssetSolrDTO(); assetSolrDTO.setScore((Float) d.getFieldValue(SolrField.SCORE.getName())); assetSolrDTO.setAverageScore((Float) d.getFieldValue(SolrField.AVERAGE_SCORE.getName())); assetSolrDTO.setReuseCounter((Integer) d.getFieldValue(SolrField.REUSE_COUNTER.getName())); assetSolrDTO.setAssetPk((String) d.getFieldValue(SolrField.ASSET_PK.getName())); assetSolrDTO.setId((String) d.getFieldValue(SolrField.ID.getName())); assetSolrDTO.setName((String) d.getFieldValue(SolrField.NAME.getName())); if (d.getFieldValue(SolrField.DATE.getName()) != null) { Calendar c = Calendar.getInstance(); c.setTime((Date) d.getFieldValue(SolrField.DATE.getName())); assetSolrDTO.setDate(c);/*ww w.j a v a 2 s . c om*/ } assetSolrDTO.setVersion((String) d.getFieldValue(SolrField.VERSION.getName())); assetSolrDTO.setType((String) d.getFieldValue(SolrField.TYPE.getName())); if (assetSolrDTO.getType().equalsIgnoreCase("OTHER")) { assetSolrDTO.setType(assetSolrDTO.getType() + " (" + (String) d.getFieldValue(SolrField.OTHER_TYPE.getName()) + ")"); } assetSolrDTO.setState((String) d.getFieldValue(SolrField.STATE.getName())); assetSolrDTO.setSoftwareLicense((String) d.getFieldValue(SolrField.SOFTWARE_LICENSE_ASSET.getName())); assetSolrDTO.setShortDescription((String) d.getFieldValue(SolrField.SHORT_DESCRIPTION.getName())); assetSolrDTO.setDescription((String) d.getFieldValue(SolrField.DESCRIPTION.getName())); if (d.getFieldValue(SolrField.CERTIFICATION_DATE.getName()) != null) { Calendar c = Calendar.getInstance(); c.setTime((Date) d.getFieldValue(SolrField.CERTIFICATION_DATE.getName())); assetSolrDTO.setCertificationDate(c); } assets.add(assetSolrDTO); } /* Normalize the relevance of the query */ if (maxScore == null) { maxScore = solrAssetDocs.getMaxScore(); } for (AssetSolrDTO a : assets) { float r = 1 + (a.getScore() * 9f) / maxScore; a.setStars((int) r); } return assets; }
From source file:co.diji.solr.XMLWriter.java
License:Apache License
public final void writeSolrDocumentList(String name, final SolrDocumentList docs, Set<String> fields) throws IOException { this.writeDocuments(name, new DocumentListInfo() { public int getCount() { return docs.size(); }/* w w w . j av a2 s .co m*/ public Float getMaxScore() { return docs.getMaxScore(); } public long getNumFound() { return docs.getNumFound(); } public long getStart() { return docs.getStart(); } public void writeDocs(boolean includeScore, Set<String> fields) throws IOException { for (SolrDocument doc : docs) { writeDoc(null, doc, fields, includeScore); } } }, fields); }
From source file:com.frank.search.solr.core.SolrTemplate.java
License:Apache License
private <T> SolrResultPage<T> createSolrResultPage(Query query, Class<T> clazz, QueryResponse response, Map<String, Object> objectsName) { List<T> beans = convertQueryResponseToBeans(response, clazz); SolrDocumentList results = response.getResults(); long numFound = results == null ? 0 : results.getNumFound(); Float maxScore = results == null ? null : results.getMaxScore(); Pageable pageRequest = query.getPageRequest(); SolrResultPage<T> page = new SolrResultPage<T>(beans, pageRequest, numFound, maxScore); page.setFieldStatsResults(/*ww w . ja v a2 s . co m*/ ResultHelper.convertFieldStatsInfoToFieldStatsResultMap(response.getFieldStatsInfo())); page.setGroupResults( ResultHelper.convertGroupQueryResponseToGroupResultMap(query, objectsName, response, this, clazz)); return page; }
From source file:com.liferay.portal.search.solr.SolrIndexSearcherImpl.java
License:Open Source License
protected Hits subset(SolrQuery solrQuery, Query query, QueryConfig queryConfig, QueryResponse queryResponse, boolean allResults) throws Exception { long startTime = System.currentTimeMillis(); Hits hits = new HitsImpl(); SolrDocumentList solrDocumentList = queryResponse.getResults(); long total = solrDocumentList.getNumFound(); if (allResults && (total > 0)) { solrQuery.setRows((int) total); queryResponse = _solrServer.query(solrQuery); return subset(solrQuery, query, queryConfig, queryResponse, false); }// w w w .j a va 2s .co m float maxScore = 1; if (queryConfig.isScoreEnabled()) { maxScore = solrDocumentList.getMaxScore(); } int subsetTotal = solrDocumentList.size(); Document[] documents = new DocumentImpl[subsetTotal]; String[] snippets = new String[subsetTotal]; float[] scores = new float[subsetTotal]; int j = 0; Set<String> queryTerms = new HashSet<String>(); Map<String, Map<String, List<String>>> highlights = queryResponse.getHighlighting(); for (SolrDocument solrDocument : solrDocumentList) { Document document = new DocumentImpl(); Collection<String> names = solrDocument.getFieldNames(); for (String name : names) { Collection<Object> fieldValues = solrDocument.getFieldValues(name); Field field = new Field(name, ArrayUtil.toStringArray(fieldValues.toArray(new Object[fieldValues.size()]))); document.add(field); } float score = 1; if (queryConfig.isScoreEnabled()) { score = GetterUtil.getFloat(String.valueOf(solrDocument.getFieldValue("score"))); } documents[j] = document; if (queryConfig.isHighlightEnabled()) { snippets[j] = getSnippet(solrDocument, queryTerms, highlights); } else { snippets[j] = StringPool.BLANK; } scores[j] = score / maxScore; j++; } float searchTime = (float) (System.currentTimeMillis() - startTime) / Time.SECOND; hits.setDocs(documents); hits.setLength((int) total); hits.setQuery(query); hits.setQueryTerms(queryTerms.toArray(new String[queryTerms.size()])); hits.setScores(scores); hits.setSearchTime(searchTime); hits.setSnippets(snippets); hits.setStart(startTime); return hits; }
From source file:com.nridge.ds.solr.SolrResponseBuilder.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) private void populateHeader(QueryResponse aQueryResponse, long anOffset, long aLimit) { Logger appLogger = mAppMgr.getLogger(this, "populateHeader"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); Relationship headerRelationship = mDocument.getFirstRelationship(Solr.RESPONSE_HEADER); if (headerRelationship != null) { DataBag headerBag = headerRelationship.getBag(); headerBag.resetValues();//from w w w .jav a2 s . co m headerBag.setValueByName("page_size", aLimit); headerBag.setValueByName("offset_start", anOffset); headerBag.setValueByName("query_time", aQueryResponse.getQTime()); String propertyName = getCfgPropertyPrefix() + ".request_handler"; String requestHandler = mAppMgr.getString(propertyName); if (StringUtils.isNotEmpty(requestHandler)) { if (requestHandler.charAt(0) == StrUtl.CHAR_FORWARDSLASH) headerBag.setValueByName("request_handler", requestHandler); else headerBag.setValueByName("request_handler", StrUtl.CHAR_FORWARDSLASH + requestHandler); } int statusCode = aQueryResponse.getStatus(); headerBag.setValueByName("status_code", statusCode); if (statusCode == Solr.RESPONSE_STATUS_SUCCESS) headerBag.setValueByName("status_message", "Success"); else headerBag.setValueByName("status_message", "Failure"); SolrDocumentList solrDocumentList = aQueryResponse.getResults(); if (solrDocumentList != null) { Float maxScore = solrDocumentList.getMaxScore(); if (maxScore == null) maxScore = (float) 0.0; headerBag.setValueByName("max_score", maxScore); headerBag.setValueByName("fetch_count", solrDocumentList.size()); long totalCount = solrDocumentList.getNumFound(); headerBag.setValueByName("total_count", totalCount); } NamedList<Object> headerList = aQueryResponse.getHeader(); if (headerList != null) { NamedList<Object> paramList = (NamedList<Object>) aQueryResponse.getResponseHeader().get("params"); if (paramList != null) { Object paramObject = paramList.get("fl"); if (paramObject != null) { DataField dataField = headerBag.getFieldByName("field_list"); if (paramObject instanceof String) dataField.addValue(paramObject.toString()); else if (paramObject instanceof List) { List fieldList = (List) paramObject; int fieldCount = fieldList.size(); if (fieldCount > 0) { for (int i = 0; i < fieldCount; i++) dataField.addValue(fieldList.get(i).toString()); } } } paramObject = paramList.get("hl"); if (paramObject != null) { DataField dataField = headerBag.getFieldByName("is_highlighted"); if (paramObject instanceof String) { if (StringUtils.equalsIgnoreCase(paramObject.toString(), "on")) dataField.setValue(true); } } } } } appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:com.smartitengineering.dao.solr.impl.DefaultSolrDao.java
License:Open Source License
@Override public SearchResult<MultivalueMap<String, Object>> getResult(SolrParams query) { boolean success = true; List<MultivalueMap<String, Object>> list = new ArrayList<MultivalueMap<String, Object>>(); SearchResult<MultivalueMap<String, Object>> result = null; try {// w w w . jav a 2s .c om final SolrServer solrServer = serverFactory.getSolrServer(); QueryResponse response = solrServer.query(query); success = response.getStatus() == 0 && success; if (success) { SolrDocumentList documentList = response.getResults(); if (logger.isInfoEnabled()) { logger.info("Solr Document List " + documentList); } if (documentList.getMaxScore() == null) { result = new SearchResult<MultivalueMap<String, Object>>(list, documentList.getNumFound()); } else { result = new SearchResult<MultivalueMap<String, Object>>(list, documentList.getNumFound(), documentList.getMaxScore()); } for (SolrDocument document : documentList) { MultivalueMap<String, Object> map = new MultivalueMapImpl<String, Object>(); list.add(map); Map<String, Collection<Object>> values = document.getFieldValuesMap(); for (String key : values.keySet()) { Collection<Object> oValues = values.get(key); for (Object value : oValues) { map.addValue(key, value); } } } } } catch (Exception ex) { logger.error("Could not search from solr index", ex); success = false; } if (result == null) { result = new SearchResult<MultivalueMap<String, Object>>(list); } return result; }
From source file:edu.ku.brc.sgr.MatchableIndexedId.java
License:Open Source License
@Override public MatchResults doMatch(SolrServer server, SolrQuery baseQuery) { final SolrQuery query = baseQuery.getCopy(); query.setQuery("id:" + id); final QueryResponse resp; try {//ww w . ja v a2 s. co m resp = server.query(query); } catch (SolrServerException e) { // TODO Auto-generated catch block throw new RuntimeException(e); } final SolrDocumentList docs = resp.getResults(); final float maxScore = (docs != null) ? docs.getMaxScore() : 0.0f; final ImmutableList.Builder<Match> msBuilder = ImmutableList.builder(); if (docs != null) { for (SolrDocument doc : docs) { float score = (Float) doc.getFieldValue("score"); SGRRecord match = SGRRecord.fromSolrDocument(doc); msBuilder.add(new Match(match, score)); } } return new MatchResults(id, resp.getQTime(), maxScore, msBuilder.build()); }
From source file:edu.ku.brc.sgr.MatchableRecord.java
License:Open Source License
@Override public MatchResults doMatch(SolrServer server, SolrQuery baseQuery) { final ModifiableSolrParams query = baseQuery.getCopy().set(MoreLikeThisParams.DOC_SUPPLIED, true); final MoreLikeThisDocumentRequest req = new MoreLikeThisDocumentRequest(query) .addDocument(record.asSolrDocument()); final QueryResponse resp; try {/* ww w. ja va2 s . co m*/ resp = req.process(server); } catch (Exception e) { // TODO Auto-generated catch block throw new RuntimeException(e); } final SolrDocumentList docs = resp.getResults(); Map<String, String> explain = resp.getExplainMap(); if (explain == null) explain = Maps.newHashMap(); final ImmutableList.Builder<Match> msBuilder = ImmutableList.builder(); final float maxScore = (docs != null) ? docs.getMaxScore() : 0.0f; if (docs != null) { for (SolrDocument doc : docs) { float score = (Float) doc.getFieldValue("score"); SGRRecord match = SGRRecord.fromSolrDocument(doc); String explained = explain.get(match.id); msBuilder.add(new Match(match, score, explained)); } } return new MatchResults(record.id, resp.getQTime(), maxScore, msBuilder.build()); }
From source file:edu.toronto.cs.phenotips.solr.AbstractSolrScriptService.java
License:Open Source License
/** * Perform a search, falling back on the suggested spellchecked query if the original query fails to return any * results./*from w w w .jav a 2s .co m*/ * * @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 { NamedList<Object> newParams = params.toNamedList(); if (newParams.get(CommonParams.FL) == null) { newParams.add(CommonParams.FL, "* score"); } QueryResponse response = this.server.query(MapSolrParams.toSolrParams(newParams)); SolrDocumentList results = response.getResults(); if (response.getSpellCheckResponse() != null && !response.getSpellCheckResponse().isCorrectlySpelled()) { String suggestedQuery = response.getSpellCheckResponse().getCollatedResult(); if (StringUtils.isEmpty(suggestedQuery)) { return results; } Pattern p = Pattern.compile("(\\w++):(\\w++)\\*$", Pattern.CASE_INSENSITIVE); Matcher originalStub = p.matcher((String) newParams.get(CommonParams.Q)); newParams.remove(CommonParams.Q); Matcher newStub = p.matcher(suggestedQuery); if (originalStub.find() && newStub.find()) { suggestedQuery += ' ' + originalStub.group() + "^1.5 " + originalStub.group(2) + "^1.5"; String boostQuery = (String) newParams.get(DisMaxParams.BQ); if (boostQuery != null) { boostQuery += ' ' + boostQuery.replace(originalStub.group(2), newStub.group(2)); newParams.remove(DisMaxParams.BQ); newParams.add(DisMaxParams.BQ, boostQuery); } } newParams.add(CommonParams.Q, suggestedQuery); SolrDocumentList spellcheckResults = this.server.query(MapSolrParams.toSolrParams(newParams)) .getResults(); if (results.getMaxScore() < spellcheckResults.getMaxScore()) { results = spellcheckResults; } } return results; } catch (SolrServerException ex) { this.logger.error("Failed to search: {}", ex.getMessage(), ex); } return null; }
From source file:eumetsat.pn.solr.webapp.SolrApp.java
@Override protected Map<String, Object> search(String searchTerms, String filterString, int from, int size) { Map<String, Object> data = new HashMap<>(); // put "session" parameters here rightaway so it can be used in template even when empty result data.put("search_terms", searchTerms == null ? "*:*" : searchTerms); data.put("filter_terms", filterString == null ? "" : filterString); Stopwatch stopwatch = Stopwatch.createStarted(); try {//from w ww .jav a 2 s . c o m SolrQuery query = new SolrQuery(); query.setQuery(searchTerms); query.setStart(from == -1 ? 0 : from); query.setRows(size); query.setFields("id", "title", "description", "thumbnail_s", "status_s", "score"); // "exclude" xmldoc query.setParam("qt", "edismax"); // probably default already // boosting query.setParam("qf", "title^10 description status^2 keywords"); // set highlight, see also https://cwiki.apache.org/confluence/display/solr/Standard+Highlighter query.setHighlight(true).setHighlightSnippets(17).setHighlightFragsize(0); // http://wiki.apache.org/solr/HighlightingParameters query.setParam("hl.preserveMulti", "true"); // preserve non-matching keywords query.setParam("hl.fl", "id", "title", "description", "keywords"); // "*"); // select fields to highlight // override defaults: query.setParam("hl.simple.pre", "<em><strong>"); query.setParam("hl.simple.post", "</strong></em>"); // configure faceting, see also http://wiki.apache.org/solr/SolrFacetingOverview and http://wiki.apache.org/solr/Solrj and https://wiki.apache.org/solr/SimpleFacetParameters and query.setFacet(true).setFacetLimit(4).setFacetMissing(true); // not in API, probably normally set in schema.xml: query.setParam("facet.field", "satellite_s", "instrument_s", "category", "societalBenefitArea_ss", "distribution_ss"); // filtering Set<String> hiddenFacets = new HashSet<>(); // hiding no facets yet if (filterString != null && !filterString.isEmpty()) { Multimap<String, String> filterTermsMap = parseFiltersTerms(filterString); if (filterTermsMap.size() > 0) { for (Map.Entry<String, String> entry : filterTermsMap.entries()) { String filter = " +" + entry.getKey() + ":" + entry.getValue(); query.addFilterQuery(filter); hiddenFacets.add(entry.getKey() + ":" + entry.getValue()); } } } data.put("tohide", hiddenFacets); log.debug("Solr query: {}", query); QueryResponse response = solr.query(query); if (response == null) { log.error("Response from {} is null!", this.name); data.put("total_hits", 0); data = addMessage(data, MessageLevel.danger, "Response is null from " + this.name); } else { log.trace("Got response: {}", response); if (response.getStatus() == 0) { List<Map<String, Object>> resHits = new ArrayList<>(); SolrDocumentList results = response.getResults(); Map<String, Map<String, List<String>>> highlights = response.getHighlighting(); data.put("total_hits", results.getNumFound()); if (results.getNumFound() < 1) { addMessage(data, MessageLevel.info, "No results found!"); } data.put("max_score", results.getMaxScore()); Map<String, Object> pagination = computePaginationParams( ((Long) (data.get("total_hits"))).intValue(), from); data.put("pagination", pagination); for (SolrDocument result : results) { HashMap<String, Object> resHit = new HashMap<>(); String currentId = (String) result.getFieldValue("id"); Map<String, List<String>> currentHighlights = highlights.get(currentId); resHit.put("id", currentId); resHit.put("score", String.format("%.4g", result.getFieldValue("score"))); resHit.put("abstract", hightlightIfGiven(result, currentHighlights, "description")); resHit.put("title", hightlightIfGiven(result, currentHighlights, "title")); resHit.put("keywords", Joiner.on(", ").join( (Collection<String>) hightlightIfGiven(result, currentHighlights, "keywords"))); resHit.put("satellite", result.get("satellite_s")); resHit.put("thumbnail", result.get("thumbnail_s")); resHit.put("status", result.get("status_s")); resHit.put("distribution", result.get("distribution_ss")); resHits.add(resHit); } data.put("hits", resHits); // faceting information: List<FacetField> facets = response.getFacetFields(); log.trace("Facets ({}): {}", facets.size(), facets); //jsObj.get("facets").get("categories").get("terms") - then term und count // convert to format of Elasticsearch: Map<String, Object> facetsJson = new HashMap<>(); for (FacetField facet : facets) { Map<String, Object> facetMap = new HashMap<>(); facetMap.put("total", facet.getValueCount()); List<Map<String, Object>> terms = new ArrayList<>(); for (Count count : facet.getValues()) { if (count.getCount() > 0) { Map<String, Object> termMap = new HashMap<>(); termMap.put("count", count.getCount()); termMap.put("term", count.getName() == null ? "N/A" : count.getName()); terms.add(termMap); } } facetMap.put("terms", terms); facetsJson.put(facet.getName(), facetMap); } data.put("facets", facetsJson); } else { // non-OK resonse log.error("Received non-200 response: {}", response); data = addMessage(data, MessageLevel.danger, "Non 200 response: " + response.toString()); } } data.put("elapsed", (double) (stopwatch.elapsed(TimeUnit.MILLISECONDS)) / (double) 1000); log.trace("Prepared data for template: {}", data); } catch (SolrServerException e) { log.error("Error querying Solr", e); addMessage(data, MessageLevel.danger, "Error during search: " + e.getMessage()); // errorResponse(e); } stopwatch.stop(); return data; }