Java Code Examples for org.apache.solr.client.solrj.SolrQuery#addSort()

The following examples show how to use org.apache.solr.client.solrj.SolrQuery#addSort() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BasicDistributedZkTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void testSortableTextSorting() throws Exception {
  SolrQuery query = new SolrQuery("*:*");
  query.addSort(tsort, SolrQuery.ORDER.desc);
  query.addField("*");
  query.addField("eoe_sortable");
  query.addField(tsort);
  QueryResponse resp = queryServer(query);

  SolrDocumentList docs = resp.getResults();

  String title = docs.get(0).getFieldValue(tsort).toString();
  for (SolrDocument doc : docs) {
    assertTrue("Docs should be back in sorted order, descending", title.compareTo(doc.getFieldValue(tsort).toString()) >= 0);
    title = doc.getFieldValue(tsort).toString();
  }
}
 
Example 2
Source File: DistributedVersionInfoTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected long getVersionFromIndex(Replica replica, String docId) throws IOException, SolrServerException {
  Long vers = null;
  String queryStr = (docId != null) ? "id:" + docId : "_version_:[0 TO *]";
  SolrQuery query = new SolrQuery(queryStr);
  query.setRows(1);
  query.setFields("id", "_version_");
  query.addSort(new SolrQuery.SortClause("_version_", SolrQuery.ORDER.desc));
  query.setParam("distrib", false);

  try (SolrClient client = getHttpSolrClient(replica.getCoreUrl())) {
    QueryResponse qr = client.query(query);
    SolrDocumentList hits = qr.getResults();
    if (hits.isEmpty())
      fail("No results returned from query: "+query);

    vers = (Long) hits.get(0).getFirstValue("_version_");
  }

  if (vers == null)
    fail("Failed to get version using query " + query + " from " + replica.getCoreUrl());

  return vers.longValue();
}
 
Example 3
Source File: DocValuesNotIndexedTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void checkSortOrder(CloudSolrClient client, List<FieldProps> props, String sortDir, String[] order, String[] orderBool) throws IOException, SolrServerException {
  for (FieldProps prop : props) {
    final SolrQuery solrQuery = new SolrQuery("q", "*:*", "rows", "100");
    solrQuery.setSort(prop.getName(), "asc".equals(sortDir) ? SolrQuery.ORDER.asc : SolrQuery.ORDER.desc);
    solrQuery.addSort("id", SolrQuery.ORDER.asc);
    final QueryResponse rsp = client.query(COLLECTION, solrQuery);
    SolrDocumentList res = rsp.getResults();
    assertEquals("Should have exactly " + order.length + " documents returned", order.length, res.getNumFound());
    String expected;
    for (int idx = 0; idx < res.size(); ++idx) {
      if (prop.getName().startsWith("bool")) expected = orderBool[idx];
      else expected = order[idx];
      assertEquals("Documents in wrong order for field: " + prop.getName(),
          expected, res.get(idx).get("id"));
    }
  }
}
 
Example 4
Source File: ServiceLogsManager.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
private SolrServiceLogData getNextHitForKeyword(ServiceLogRequest request, String keyword, boolean isNext, String event, boolean timeAscending, String nextOrPreviousPageDate) {
  if (hasNextOrAscOrder(isNext, timeAscending)) {
    request.setTo(nextOrPreviousPageDate);
  } else {
    request.setFrom(nextOrPreviousPageDate);
  }
  SimpleQuery keywordNextQuery = conversionService.convert(request, SimpleQuery.class);
  keywordNextQuery.addFilterQuery(new SimpleFilterQuery(new Criteria(KEY_LOG_MESSAGE).contains(keyword)));
  keywordNextQuery.setRows(1);
  SolrQuery kewordNextSolrQuery = new DefaultQueryParser().doConstructSolrQuery(keywordNextQuery);
  kewordNextSolrQuery.setStart(0);
  if (hasNextOrAscOrder(isNext, timeAscending)) {
    kewordNextSolrQuery.setSort(LOGTIME, SolrQuery.ORDER.desc);
  } else {
    kewordNextSolrQuery.setSort(LOGTIME, SolrQuery.ORDER.asc);
  }
  kewordNextSolrQuery.addSort(SEQUENCE_ID, SolrQuery.ORDER.desc);
  QueryResponse queryResponse = serviceLogsSolrDao.process(kewordNextSolrQuery, event);
  if (queryResponse == null) {
    throw new NotFoundException(String.format("The keyword \"%s\" was not found", keyword));
  }
  List<SolrServiceLogData> solrServiceLogDataList = queryResponse.getBeans(SolrServiceLogData.class);
  if (!CollectionUtils.isNotEmpty(solrServiceLogDataList)) {
    throw new NotFoundException(String.format("The keyword \"%s\" was not found", keyword));
  }
  return solrServiceLogDataList.get(0);
}
 
Example 5
Source File: Solr6Index.java    From atlas with Apache License 2.0 5 votes vote down vote up
private void addOrderToQuery(SolrQuery solrQuery, List<IndexQuery.OrderEntry> orders) {
    for (final IndexQuery.OrderEntry order1 : orders) {
        final String item = order1.getKey();
        final SolrQuery.ORDER order = order1.getOrder() == Order.ASC ? SolrQuery.ORDER.asc : SolrQuery.ORDER.desc;
        solrQuery.addSort(new SolrQuery.SortClause(item, order));
    }
}
 
Example 6
Source File: DefaultQueryParser.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * Append sorting parameters to
 * {@link org.apache.solr.client.solrj.SolrQuery}
 * 
 * @param solrQuery
 * @param sort
 */
protected void appendSort(SolrQuery solrQuery, Sort sort) {
	if (sort == null) {
		return;
	}

	for (Order order : sort) {
		solrQuery.addSort(order.getProperty(), order.isAscending() ? ORDER.asc : ORDER.desc);
	}
}
 
Example 7
Source File: MCRConditionTransformer.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public static SolrQuery applySortOptions(SolrQuery q, List<MCRSortBy> sortBy) {
    for (MCRSortBy option : sortBy) {
        SortClause sortClause = new SortClause(option.getFieldName(), option.getSortOrder() ? ORDER.asc
            : ORDER.desc);
        q.addSort(sortClause);
    }
    return q;
}
 
Example 8
Source File: SolrSearchDao.java    From metron with Apache License 2.0 5 votes vote down vote up
protected SolrQuery buildSearchRequest(
    SearchRequest searchRequest, String fieldList) throws IOException, SolrServerException {
  SolrQuery query = new SolrQuery()
      .setStart(searchRequest.getFrom())
      .setRows(searchRequest.getSize())
      .setQuery(searchRequest.getQuery())
      .setShowDebugInfo(LOG.isDebugEnabled()); // tie Solr query debug output to our log level

  // handle sort fields
  for (SortField sortField : searchRequest.getSort()) {
    query.addSort(sortField.getField(), getSolrSortOrder(sortField.getSortOrder()));
  }

  // handle search fields
  List<String> fields = searchRequest.getFields();
  if (fieldList == null) {
    fieldList = "*";
    if (fields != null) {
      fieldList = StringUtils.join(fields, ",");
    }
  }
  query.set("fl", fieldList);

  //handle facet fields
  List<String> facetFields = searchRequest.getFacetFields();
  if (facetFields != null) {
    facetFields.forEach(query::addFacetField);
  }

  query.set("collection", getCollections(searchRequest.getIndices()));

  return query;
}
 
Example 9
Source File: AmbariInfraWithStormLogSearch.java    From streamline with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public LogSearchResult search(LogSearchCriteria logSearchCriteria) {
    SolrQuery query = new SolrQuery();

    query.setQuery(buildColumnAndValue(COLUMN_NAME_LOG_MESSAGE, buildValue(logSearchCriteria.getSearchString())));
    query.addFilterQuery(buildColumnAndValue(COLUMN_NAME_TYPE, COLUMN_VALUE_TYPE_WORKER_LOG));
    query.addFilterQuery(buildColumnAndValue(COLUMN_NAME_STREAMLINE_TOPOLOGY_ID, buildValue(logSearchCriteria.getAppId())));
    query.addFilterQuery(buildColumnAndValue(COLUMN_NAME_LOG_TIME, buildDateRangeValue(logSearchCriteria.getFrom(), logSearchCriteria.getTo())));

    List<String> componentNames = logSearchCriteria.getComponentNames();
    if (componentNames != null && !componentNames.isEmpty()) {
        query.addFilterQuery(buildColumnAndValue(COLUMN_NAME_STREAMLINE_COMPONENT_NAME, buildORValues(componentNames)));
    }

    List<String> logLevels = logSearchCriteria.getLogLevels();
    if (logLevels == null || logLevels.isEmpty()) {
        logLevels = DEFAULT_LOG_LEVELS;
    }
    query.addFilterQuery(buildColumnAndValue(COLUMN_NAME_LOG_LEVEL, buildORValues(logLevels)));

    if (logSearchCriteria.getAscending() == null || logSearchCriteria.getAscending()) {
        query.addSort(COLUMN_NAME_LOG_TIME, SolrQuery.ORDER.asc);
    } else {
        query.addSort(COLUMN_NAME_LOG_TIME, SolrQuery.ORDER.desc);
    }

    if (logSearchCriteria.getStart() != null) {
        query.setStart(logSearchCriteria.getStart());
    }
    if (logSearchCriteria.getLimit() != null) {
        query.setRows(logSearchCriteria.getLimit());
    }

    LOG.debug("Querying to Solr: query => {}", query);

    long numFound;
    List<LogSearchResult.LogDocument> results = new ArrayList<>();
    try {
        QueryResponse response = solr.query(query);

        SolrDocumentList docList = response.getResults();
        numFound = docList.getNumFound();

        for (SolrDocument document : docList) {
            String appId = (String) document.getFieldValue(COLUMN_NAME_STREAMLINE_TOPOLOGY_ID);
            String componentName = (String) document.getFieldValue(COLUMN_NAME_STREAMLINE_COMPONENT_NAME);
            String logLevel = (String) document.getFieldValue(COLUMN_NAME_LOG_LEVEL);
            String logMessage = (String) document.getFieldValue(COLUMN_NAME_LOG_MESSAGE);
            String host = (String) document.getFieldValue(COLUMN_NAME_HOST);
            String port = (String) document.getFieldValue(COLUMN_NAME_STORM_WORKER_PORT);
            Date logDate = (Date) document.getFieldValue(COLUMN_NAME_LOG_TIME);
            long timestamp = logDate.toInstant().toEpochMilli();

            LogSearchResult.LogDocument logDocument = new LogSearchResult.LogDocument(appId, componentName,
                    logLevel, logMessage, host, port != null ? Integer.parseInt(port) : null, timestamp);
            results.add(logDocument);
        }

    } catch (SolrServerException | IOException e) {
        // TODO: any fine-grained control needed?
        throw new RuntimeException(e);
    }

    return new LogSearchResult(numFound, results);
}
 
Example 10
Source File: AmbariInfraWithStormLogSearch.java    From streamline with Apache License 2.0 4 votes vote down vote up
@Override
public EventSearchResult searchEvent(EventSearchCriteria criteria) {
    SolrQuery query = new SolrQuery();

    String searchString = criteria.getSearchString();

    List<String> queryStrings = new ArrayList<>();
    addQueryStringToListOnlyIfAvailable(queryStrings, searchString, COLUMN_NAME_STREAMLINE_EVENT_KEYVALUES);
    addQueryStringToListOnlyIfAvailable(queryStrings, searchString, COLUMN_NAME_STREAMLINE_EVENT_HEADERS);
    addQueryStringToListOnlyIfAvailable(queryStrings, searchString, COLUMN_NAME_STREAMLINE_EVENT_AUX_KEYVALUES);

    // this is to get rid of non-streamline events
    String queryString = buildColumnAndValue(COLUMN_NAME_STREAMLINE_EVENT_ID, buildValue(null));

    if (!queryStrings.isEmpty()) {
        queryString += " AND (" + String.join(" OR ", queryStrings) + ")";
    }

    query.setQuery(queryString);

    query.addFilterQuery(buildColumnAndValue(COLUMN_NAME_TYPE, COLUMN_VALUE_TYPE_EVENT));
    query.addFilterQuery(buildColumnAndValue(COLUMN_NAME_STREAMLINE_TOPOLOGY_ID, buildValue(criteria.getAppId())));
    query.addFilterQuery(buildColumnAndValue(COLUMN_NAME_LOG_TIME, buildDateRangeValue(criteria.getFrom(), criteria.getTo())));

    List<String> componentNames = criteria.getComponentNames();
    if (componentNames != null && !componentNames.isEmpty()) {
        query.addFilterQuery(buildColumnAndValue(COLUMN_NAME_STREAMLINE_COMPONENT_NAME, buildORValues(componentNames)));
    }

    String searchEventId = criteria.getSearchEventId();
    if (searchEventId != null) {
        // eventId OR rootId OR parentId
        String queryToEventId = buildColumnAndValue(COLUMN_NAME_STREAMLINE_EVENT_ID, buildValue(searchEventId));
        String queryToRootIds = buildColumnAndValue(COLUMN_NAME_STREAMLINE_EVENT_ROOT_ID_SET, buildValue("*" + searchEventId + "*"));
        String queryToParentIds = buildColumnAndValue(COLUMN_NAME_STREAMLINE_EVENT_PARENT_ID_SET, buildValue("*" + searchEventId + "*"));
        query.addFilterQuery(queryToEventId + " OR " + queryToRootIds + " OR " + queryToParentIds);
    }

    if (criteria.getAscending() == null || criteria.getAscending()) {
        query.addSort(COLUMN_NAME_LOG_TIME, SolrQuery.ORDER.asc);
    } else {
        query.addSort(COLUMN_NAME_LOG_TIME, SolrQuery.ORDER.desc);
    }

    if (criteria.getStart() != null) {
        query.setStart(criteria.getStart());
    }
    if (criteria.getLimit() != null) {
        query.setRows(criteria.getLimit());
    }

    LOG.debug("Querying to Solr: query => {}", query);

    long numFound;
    List<EventSearchResult.Event> results = new ArrayList<>();
    try {
        QueryResponse response = solr.query(query);

        SolrDocumentList docList = response.getResults();
        numFound = docList.getNumFound();

        for (SolrDocument document : docList) {
            String appId = (String) document.getFieldValue(COLUMN_NAME_STREAMLINE_TOPOLOGY_ID);
            String componentName = (String) document.getFieldValue(COLUMN_NAME_STREAMLINE_COMPONENT_NAME);
            String eventId = (String) document.getFieldValue(COLUMN_NAME_STREAMLINE_EVENT_ID);
            String rootIds = (String) document.getFieldValue(COLUMN_NAME_STREAMLINE_EVENT_ROOT_ID_SET);
            String parentIds = (String) document.getFieldValue(COLUMN_NAME_STREAMLINE_EVENT_PARENT_ID_SET);
            String keyValues = (String) document.getFieldValue(COLUMN_NAME_STREAMLINE_EVENT_KEYVALUES);
            String headers = (String) document.getFieldValue(COLUMN_NAME_STREAMLINE_EVENT_HEADERS);
            String auxKeyValues = (String) document.getFieldValue(COLUMN_NAME_STREAMLINE_EVENT_AUX_KEYVALUES);

            Date logDate = (Date) document.getFieldValue(COLUMN_NAME_LOG_TIME);
            long timestamp = logDate.toInstant().toEpochMilli();

            EventSearchResult.Event event = new EventSearchResult.Event(appId, componentName,
                    eventId, rootIds, parentIds, keyValues, headers, auxKeyValues, timestamp);
            results.add(event);
        }

    } catch (SolrServerException | IOException e) {
        // TODO: any fine-grained control needed?
        throw new RuntimeException(e);
    }

    return new EventSearchResult(numFound, results);
}