List of usage examples for org.apache.solr.client.solrj SolrQuery SolrQuery
public SolrQuery()
From source file:edu.usu.sdl.openstorefront.service.SearchServiceImpl.java
License:Apache License
@Override public List<ComponentSearchView> getSearchItems(SearchQuery query, FilterQueryParams filter) { // use for advanced search with And - Or combinations on separate fields String queryOperator = " " + SolrAndOr.OR + " "; String myQueryString;/*from ww w . j a va 2 s . co m*/ // If incoming query string is blank, default to solar *:* for the full query if (StringUtils.isNotBlank(query.getQuery())) { StringBuilder queryData = new StringBuilder(); Field fields[] = SolrComponentModel.class.getDeclaredFields(); for (Field field : fields) { org.apache.solr.client.solrj.beans.Field fieldAnnotation = field .getAnnotation(org.apache.solr.client.solrj.beans.Field.class); if (fieldAnnotation != null && field.getType() == String.class) { String name = field.getName(); if (StringUtils.isNotBlank(fieldAnnotation.value()) && org.apache.solr.client.solrj.beans.Field.DEFAULT .equals(fieldAnnotation.value()) == false) { name = fieldAnnotation.value(); } queryData.append(SolrEquals.EQUAL.getSolrOperator()).append(name) .append(SolrManager.SOLR_QUERY_SEPERATOR).append(query.getQuery()) .append(queryOperator); } } myQueryString = queryData.toString(); if (myQueryString.endsWith(queryOperator)) { queryData.delete((myQueryString.length() - (queryOperator.length())), myQueryString.length()); myQueryString = queryData.toString(); } } else { myQueryString = SolrManager.SOLR_ALL_QUERY; } log.log(Level.FINER, myQueryString); // execute the searchComponent method and bring back from solr a list array List<SolrComponentModel> resultsList = new ArrayList<>(); try { SolrQuery solrQuery = new SolrQuery(); solrQuery.setQuery(myQueryString); // fields to be returned back from solr solrQuery.setFields(SolrComponentModel.ID_FIELD, SolrComponentModel.ISCOMPONENT_FIELD); solrQuery.setStart(filter.getOffset()); solrQuery.setRows(filter.getMax()); Field sortField = ReflectionUtil.getField(new SolrComponentModel(), filter.getSortField()); if (sortField != null) { String sortFieldText = filter.getSortField(); org.apache.solr.client.solrj.beans.Field fieldAnnotation = sortField .getAnnotation(org.apache.solr.client.solrj.beans.Field.class); if (fieldAnnotation != null) { sortFieldText = fieldAnnotation.value(); } SolrQuery.ORDER order = SolrQuery.ORDER.desc; if (OpenStorefrontConstant.SORT_ASCENDING.equalsIgnoreCase(filter.getSortOrder())) { order = SolrQuery.ORDER.asc; } solrQuery.addSort(sortFieldText, order); } solrQuery.setIncludeScore(true); QueryResponse response = SolrManager.getServer().query(solrQuery); SolrDocumentList results = response.getResults(); DocumentObjectBinder binder = new DocumentObjectBinder(); resultsList = binder.getBeans(SolrComponentModel.class, results); } catch (SolrServerException ex) { throw new OpenStorefrontRuntimeException("Search Failed", "Contact System Admin. Seach server maybe Unavailable", ex); } catch (Exception ex) { log.log(Level.WARNING, "Solr query failed unexpectly; likely bad input.", ex); } //Pulling the full object on the return List<ComponentSearchView> views = new ArrayList<>(); List<String> componentIds = new ArrayList<>(); for (SolrComponentModel result : resultsList) { if (result.getIsComponent()) { componentIds.add(result.getId()); } } //remove bad indexes, if any List<ComponentSearchView> componentSearchViews = getComponentService().getSearchComponentList(componentIds); Set<String> goodComponentIdSet = new HashSet<>(); for (ComponentSearchView view : componentSearchViews) { goodComponentIdSet.add(view.getComponentId()); } for (String componentId : componentIds) { if (goodComponentIdSet.contains(componentId) == false) { log.log(Level.FINE, MessageFormat.format("Removing bad index: {0}", componentId)); deleteById(componentId); } } views.addAll(componentSearchViews); List<ComponentSearchView> articleViews = getAttributeService().getArticlesSearchView(); Map<String, ComponentSearchView> allViews = new HashMap<>(); for (ComponentSearchView componentSearchView : articleViews) { AttributeCodePk attributeCodePk = new AttributeCodePk(); attributeCodePk.setAttributeType(componentSearchView.getArticleAttributeType()); attributeCodePk.setAttributeCode(componentSearchView.getArticleAttributeCode()); allViews.put(attributeCodePk.toKey(), componentSearchView); } for (SolrComponentModel result : resultsList) { if (result.getIsComponent() == false) { ComponentSearchView view = allViews.get(result.getId()); if (view != null) { views.add(view); } else { log.log(Level.FINE, MessageFormat.format("Removing bad index: {0}", result.getId())); deleteById(result.getId()); } } } //TODO: Get the score and sort by score return views; }
From source file:edu.vt.vbi.patric.common.DataApiHandler.java
License:Apache License
/** * wrapper function of field facet query * * @param core SolrCore/*from ww w. j ava 2 s . co m*/ * @param queryParam query condition * @param filterParam filter condition * @param facetFields comma separated list of fields */ public Map getFieldFacets(SolrCore core, String queryParam, String filterParam, String facetFields) throws IOException { Map<String, Object> res = new HashMap<>(); SolrQuery query = new SolrQuery(); query.setQuery(queryParam); if (filterParam != null) { query.addFilterQuery(filterParam); } query.setRows(0).setFacet(true).setFacetLimit(-1).setFacetMinCount(1) .setFacetSort(FacetParams.FACET_SORT_COUNT).set("json.nl", "map"); query.addFacetField(facetFields.split(",")); List<String> fields = Arrays.asList(facetFields.split(",")); LOGGER.trace("getFieldFacets: [{}] {}", core.getSolrCoreName(), query.toString()); String response = this.solrQuery(core, query); Map resp = jsonParser.readValue(response); Map facet_fields = (Map) ((Map) resp.get("facet_counts")).get("facet_fields"); Map<String, Object> facets = new HashMap<>(); for (String field : fields) { Map values = (Map) facet_fields.get(field); Map<String, Integer> facetValues = new LinkedHashMap<>(); for (Map.Entry<String, Integer> entry : (Iterable<Map.Entry>) values.entrySet()) { facetValues.put(entry.getKey(), entry.getValue()); } facets.put(field, facetValues); } res.put("total", ((Map) resp.get("response")).get("numFound")); res.put("facets", facets); return res; }
From source file:edu.vt.vbi.patric.common.DataApiHandler.java
License:Apache License
/** * wrapper function of pivot facet query * * @param core SolrCore/*from w w w .java 2s . co m*/ * @param queryParam query condition * @param filterParam filter condition * @param facetFields comma separated list of fields */ public Map getPivotFacets(SolrCore core, String queryParam, String filterParam, String facetFields) throws IOException { Map<String, Object> res = new HashMap<>(); SolrQuery query = new SolrQuery(); query.setQuery(queryParam); if (filterParam != null) { query.addFilterQuery(filterParam); } query.setRows(0).setFacet(true).setFacetLimit(-1).setFacetMinCount(1) .setFacetSort(FacetParams.FACET_SORT_INDEX); query.addFacetPivotField(facetFields); LOGGER.trace("getPivotFacets: [{}] {}", core.getSolrCoreName(), query.toString()); String response = this.solrQuery(core, query); Map<String, Object> resp = jsonParser.readValue(response); Map facet_fields = (Map) ((Map) resp.get("facet_counts")).get("facet_pivot"); List<Map> values = (List) facet_fields.get(facetFields); Map<String, Object> facet = new LinkedHashMap<>(); for (Map value : values) { String localKey = value.get("value").toString(); List<Map> localValues = (List) value.get("pivot"); Map<String, Integer> pivotValues = new LinkedHashMap<>(); for (Map local : localValues) { pivotValues.put(local.get("value").toString(), (Integer) local.get("count")); } facet.put(localKey, pivotValues); } res.put("total", ((Map) resp.get("response")).get("numFound")); res.put(facetFields, facet); return res; }
From source file:edu.vt.vbi.patric.common.DataApiHandler.java
License:Apache License
public SolrQuery buildSolrQuery(Map<String, String> key, String sorts, String facets, int start, int end, boolean highlight) { SolrQuery query = new SolrQuery(); SolrInterface solr = new SolrInterface(); // Processing key map query.setQuery(StringHelper.stripQuoteAndParseSolrKeywordOperator(key.get("keyword"))); if (key.containsKey("filter") && key.get("filter") != null) { query.addFilterQuery(key.get("filter")); }// www.j a v a 2 s. co m if (key.containsKey("filter2") && key.get("filter2") != null) { query.addFilterQuery(key.get("filter2")); } // use SolrJoin if possible if (key.containsKey("join")) { query.addFilterQuery(key.get("join")); } if (key.containsKey("fields") && !key.get("fields").equals("")) { query.addField(key.get("fields")); } // sort conditions if (sorts != null && !sorts.equals("") && !sorts.equals("[]")) { try { JSONArray sorter = (JSONArray) new JSONParser().parse(sorts); for (Object aSort : sorter) { JSONObject jsonSort = (JSONObject) aSort; query.addSort(SolrQuery.SortClause.create(jsonSort.get("property").toString(), jsonSort.get("direction").toString().toLowerCase())); } } catch (ParseException e) { LOGGER.error(e.getMessage(), e); } } // facet conditions if (facets != null && !facets.equals("") && !facets.equals("{}")) { query.setFacet(true).setFacetMinCount(1).setFacetLimit(-1).setFacetSort(FacetParams.FACET_SORT_COUNT) .set("json.nl", "map"); try { JSONObject facetConditions = (JSONObject) new JSONParser().parse(facets); if (facetConditions.containsKey("facet.sort")) { String facetSort = facetConditions.get("facet.sort").toString(); if (facetSort.equals("index")) { query.setFacetSort(FacetParams.FACET_SORT_INDEX); } } if (facetConditions.containsKey("field_facets")) { String[] fieldFacets = facetConditions.get("field_facets").toString().split(","); query.addFacetField(fieldFacets); } if (facetConditions.containsKey("date_range_facets") && !facetConditions.get("date_range_facets").equals("")) { String[] dateRangeFacets = facetConditions.get("date_range_facets").toString().split(","); for (String field : dateRangeFacets) { query.addDateRangeFacet(field, solr.getRangeStartDate(), solr.getRangeEndDate(), solr.getRangeDate()); } } } catch (ParseException e) { LOGGER.error(e.getMessage(), e); } } // start & end query.setStart(start); // setting starting index if (end == -1) { query.setRows(MAX_ROWS); } else { query.setRows(end); } // highlight if (highlight) { query.set("hl", "on").set("hl.fl", "*"); } return query; }
From source file:edu.vt.vbi.patric.common.FacetHelper.java
License:Apache License
private static JSONObject getSingleFacetsData(DataApiHandler dataApi, SolrCore core, String keyword, String single_facet, String[] facets, String fq) throws IOException, ParseException { SolrInterface solr = new SolrInterface(); keyword = StringHelper.stripQuoteAndParseSolrKeywordOperator(keyword); int beginindex = keyword.indexOf(" AND (" + single_facet); int endindex = 0; StringBuffer s = new StringBuffer(keyword); if (beginindex < 0) { beginindex = keyword.indexOf("(" + single_facet); endindex = keyword.indexOf(") AND ", beginindex); if (endindex < 0) { endindex = keyword.indexOf("))", beginindex); // TODO: this cause java.lang.StringIndexOutOfBoundsException: String index out of range: -1 // when Patric Libs keyword - (*) and endindex: 2 LOGGER.debug("string:{}, beginIndex: {}, endIndex:{}", s, beginindex, endindex); if (endindex > 0) { s.delete(beginindex, endindex + 2); }//from w w w. j av a2 s .co m } else { s.delete(beginindex, endindex + 6); } } else { endindex = keyword.indexOf("))", beginindex); if (endindex == -1) { endindex = keyword.indexOf("])", beginindex); } s.delete(beginindex, endindex + 2); } if (s.length() == 0) s.append("(*)"); SolrQuery query = new SolrQuery(); query.setQuery(s.toString()); if (fq != null) { query.setFilterQueries(fq); } query.setStart(0).setRows(1).setFacet(true).setFacetMinCount(1).set("json.nl", "map"); for (String facet : facets) { if (!facet.equals("completion_date") && !facet.equals("release_date")) { query.addFacetField(facet); } else { query.addDateRangeFacet(facet, solr.getRangeStartDate(), solr.getRangeEndDate(), solr.getRangeDate()); } } String apiResponse = dataApi.solrQuery(core, query); Map resp = jsonMapReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); JSONObject ret = new JSONObject(); ret.put("response", new JSONObject(respBody)); ret.put("facets", FacetHelper.formatFacetTree((Map) resp.get("facet_counts"))); return ret; }
From source file:edu.vt.vbi.patric.common.SolrInterface.java
License:Apache License
public String getProteomicsTaxonIdFromFeatureId(String id) { SolrQuery query = new SolrQuery(); query.setQuery("na_feature_id:" + id); query.setRows(1000000);// w w w .j a va 2s. c o m String experiment_id = ""; // try { // QueryResponse qr = server.query(query); // SolrDocumentList sdl = qr.getResults(); // // for (SolrDocument d : sdl) { // for (Entry<String, Object> el : d) { // if (el.getKey().equals("experiment_id")) { // if (experiment_id.length() == 0) // experiment_id = el.getValue().toString(); // else // experiment_id += "##" + el.getValue().toString(); // } // } // } // } // catch (SolrServerException e) { // e.printStackTrace(); // } return experiment_id; }