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

The following examples show how to use org.apache.solr.client.solrj.SolrQuery#setStart() . 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: AbstractDateRangeFacetQueryConverter.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Override
public SolrQuery convert(SOURCE request) {
  SolrQuery solrQuery = new SolrQuery();
  String unit = StringUtils.defaultIfEmpty(request.getUnit(), "+1HOUR");
  solrQuery.setQuery("*:*");
  solrQuery.setFacet(true);
  solrQuery.addFacetPivotField("{!range=r1}" + getTypeFieldName());
  solrQuery.setFacetMinCount(1);
  solrQuery.setFacetLimit(-1);
  solrQuery.setFacetSort(LogSearchConstants.FACET_INDEX);
  solrQuery.add("facet.range", "{!tag=r1}" + getDateFieldName());
  solrQuery.add(String.format(Locale.ROOT, "f.%s.%s", getDateFieldName(), "facet.range.start"), request.getFrom());
  solrQuery.add(String.format(Locale.ROOT, "f.%s.%s", getDateFieldName(), "facet.range.end"), request.getTo());
  solrQuery.add(String.format(Locale.ROOT, "f.%s.%s", getDateFieldName(), "facet.range.gap"), unit);
  solrQuery.remove("sort");
  solrQuery.setRows(0);
  solrQuery.setStart(0);
  return solrQuery;
}
 
Example 2
Source File: ItemSearchServiceLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenSearchingByBasicQuery_thenAllMatchingItemsShouldAvialble() throws Exception {
    itemSearchService.index("hm0001", "Brand1 Washing Machine", "Home Appliances", 450f);
    itemSearchService.index("hm0002", "Brand1 Refrigerator", "Home Appliances", 450f);
    itemSearchService.index("hm0003", "LED TV 32", "Brand1 Home Appliances", 450f);

    SolrQuery query = new SolrQuery();
    query.setQuery("brand1");
    query.setStart(0);
    query.setRows(10);

    QueryResponse response = solrClient.query(query);
    List<Item> items = response.getBeans(Item.class);

    assertEquals(3, items.size());

}
 
Example 3
Source File: TestSolr.java    From DistributedCrawler with Apache License 2.0 6 votes vote down vote up
@Test
public void testSearch() throws SolrServerException{
	String url = "http://localhost:8888/solr";
	  SolrServer server = new HttpSolrServer(url);
	  SolrQuery query = new SolrQuery("火箭");
	  query.setStart(0);
	  query.setRows(100);
	   QueryResponse response = server.query(query);
	   SolrDocumentList docs = response.getResults();
	   System.out.println("文档个数:" + docs.getNumFound());
	   System.out.println("查询时间:" + response.getQTime());
	   for (SolrDocument doc : docs) {
	    System.out.println("id: " + doc.getFieldValue("id"));
	    System.out.println("title: " + doc.getFieldValue("title"));
	    System.out.println("contect: "+doc.getFieldValue("content"));
	   }
}
 
Example 4
Source File: MCRSwordSolrObjectIDSupplier.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public long getCount() throws SwordServerException {
    try {
        // make a copy to prevent multi threading issues
        final SolrQuery queryCopy = this.solrQuery.getCopy();

        // only need the numFound
        queryCopy.setStart(0);
        queryCopy.setRows(0);
        final QueryResponse queryResponse = MCRSolrClientFactory.getMainSolrClient().query(queryCopy);

        return queryResponse.getResults().getNumFound();
    } catch (SolrServerException | IOException e) {
        throw new SwordServerException(
            "Error while getting count with MCRSword2SolrObjectIDSupplier and Query: " + this.solrQuery,
            e);
    }
}
 
Example 5
Source File: MCRSwordSolrObjectIDSupplier.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<MCRObjectID> get(int from, int count) throws SwordServerException {
    final SolrQuery queryCopy = this.solrQuery.getCopy();
    queryCopy.setStart(from);
    queryCopy.setRows(count);
    try {
        final QueryResponse queryResponse = MCRSolrClientFactory.getMainSolrClient().query(queryCopy);
        return queryResponse.getResults().stream()
            .map(r -> (String) r.getFieldValue("id"))
            .map(MCRObjectID::getInstance)
            .collect(Collectors.toList());
    } catch (SolrServerException | IOException e) {
        throw new SwordServerException("Error while getting id list with MCRSword2SolrObjectIDSupplier and Query: "
            + this.solrQuery, e);
    }
}
 
Example 6
Source File: SolrStreamingService.java    From chronix.spark with Apache License 2.0 6 votes vote down vote up
private void initialStream(SolrQuery query, SolrClient connection) {
    try {
        SolrQuery solrQuery = query.getCopy();
        solrQuery.setRows(nrOfTimeSeriesPerBatch);
        solrQuery.setStart(currentDocumentCount);

        solrStreamingHandler.init(nrOfTimeSeriesPerBatch, currentDocumentCount);
        QueryResponse response = connection.queryAndStreamResponse(solrQuery, solrStreamingHandler);

        nrOfAvailableTimeSeries = response.getResults().getNumFound();
        queryStart = 0;//(long) response.getResponseHeader().get(ChronixSolrStorageConstants.QUERY_START_LONG);
        queryEnd = Long.MAX_VALUE;//(long) response.getResponseHeader().get(ChronixSolrStorageConstants.QUERY_END_LONG);

        needStream = false;
    } catch (SolrServerException | IOException e) {
        LOGGER.error("SolrServerException occurred while querying server.", e);
    }
}
 
Example 7
Source File: SolrStreamingService.java    From chronix.server with Apache License 2.0 6 votes vote down vote up
private void initialStream(SolrQuery query, SolrClient connection) {
    try {
        //Make a copy of the query
        SolrQuery solrQuery = query.getCopy();
        //We override the number of rows
        solrQuery.setRows(nrOfTimeSeriesPerBatch);
        //And the start
        solrQuery.setStart(currentDocumentCount);
        //init the streaming handler with
        solrStreamingHandler.init(nrOfTimeSeriesPerBatch, currentDocumentCount);
        QueryResponse response = connection.queryAndStreamResponse(solrQuery, solrStreamingHandler);
        //Set the global values
        nrOfAvailableTimeSeries = response.getResults().getNumFound();
        queryStart = (long) response.getResponseHeader().get(ChronixSolrStorageConstants.QUERY_START_LONG);
        queryEnd = (long) response.getResponseHeader().get(ChronixSolrStorageConstants.QUERY_END_LONG);
        //Data is filled. We need not stream until it is read out
        needStream = false;
    } catch (SolrServerException | IOException e) {
        LOGGER.error("SolrServerException occurred while querying server.", e);
    }
}
 
Example 8
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 9
Source File: SolrSteps.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
@Then("the number of <component> docs is: <docSize>")
public void numberOfDocsForComponent(@Named("component") String component, @Named("docSize") int docSize)
  throws IOException, SolrServerException, InterruptedException {
  SolrClient solrClient = StoryDataRegistry.INSTANCE.getSolrClient();
  SolrQuery solrQuery = new SolrQuery();
  solrQuery.setQuery(String.format("type:%s", component));
  solrQuery.setStart(0);
  solrQuery.setRows(20);
  QueryResponse queryResponse = solrClient.query(solrQuery);
  SolrDocumentList list = queryResponse.getResults();
  Assert.assertEquals(docSize, list.size());
}
 
Example 10
Source File: SearchServiceImpl.java    From learning-taotaoMall with MIT License 5 votes vote down vote up
@Override
public SearchResult search(String queryString, int page, int rows) throws Exception {
	//创建查询对象
	SolrQuery query = new SolrQuery();
	//设置查询条件
	query.setQuery(queryString);
	//设置分页
	query.setStart((page - 1) * rows);
	query.setRows(rows);
	//设置默认搜素域
	query.set("df", "item_keywords");
	//设置高亮显示
	query.setHighlight(true);
	query.addHighlightField("item_title");
	query.setHighlightSimplePre("<em style=\"color:red\">");
	query.setHighlightSimplePost("</em>");
	//执行查询
	SearchResult searchResult = searchDao.search(query);
	//计算查询结果总页数
	long recordCount = searchResult.getRecordCount();
	long pageCount = recordCount / rows;
	if (recordCount % rows > 0) {
		pageCount++;
	}
	searchResult.setPageCount(pageCount);
	searchResult.setCurPage(page);

	return searchResult;
}
 
Example 11
Source File: QueryParserBase.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * Append pagination information {@code start, rows} to
 * {@link org.apache.solr.client.solrj.SolrQuery}
 *
 * @param query
 * @param offset
 * @param rows
 */
protected void appendPagination(SolrQuery query, Integer offset, Integer rows) {

	if (offset != null && offset.intValue() >= 0) {
		query.setStart(offset);
	}
	if (rows != null && rows.intValue() >= 0) {
		query.setRows(rows);
	}
}
 
Example 12
Source File: SolrEntityProcessor.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
protected void passNextPage(SolrQuery solrQuery) {
  String timeoutAsString = context.getResolvedEntityAttribute(TIMEOUT);
  if (timeoutAsString != null) {
    SolrEntityProcessor.this.timeout = Integer.parseInt(timeoutAsString);
  }
  
  solrQuery.setTimeAllowed(timeout * 1000);
  
  solrQuery.setStart(getStart() + getSize());
}
 
Example 13
Source File: SolrMachineProducer.java    From extract with MIT License 5 votes vote down vote up
private long fetch() throws IOException, SolrServerException {
	final SolrQuery query = new SolrQuery(filter);

	query.setRows(rows);
	query.setStart((int) start);

	// Only request the fields to be copied and the ID.
	query.setFields(idField);

	if (null != fields) {
		fields.forEach(query::addField);
	}

	logger.info(String.format("Fetching up to %d documents, skipping %d.", rows, start));
	client.queryAndStreamResponse(query, this);

	final long fetched = this.fetched;

	// Stop if there are no more results.
	// Instruct transformers to stop by sending a poison pill.
	if (fetched < rows) {
		stopped = true;
	}

	// Reset for the next run.
	this.fetched = 0;
	return fetched;
}
 
Example 14
Source File: SolrOntologySearch.java    From BioSolr with Apache License 2.0 5 votes vote down vote up
@Override
public ResultsList<OntologyEntryBean> searchOntology(String term, List<String> filters, int start, int rows, List<String> fields) throws SearchEngineException {
	ResultsList<OntologyEntryBean> results = null;
	
	try {
		SolrQuery query = new SolrQuery(term);
		if (filters != null && !filters.isEmpty()) {
			query.addFilterQuery(filters.toArray(new String[filters.size()]));
		}
		if (fields != null && !fields.isEmpty()) {
			query.setFields(fields.toArray(new String[fields.size()]));
		}
		query.setStart(start);
		query.setRows(rows);
		query.setRequestHandler(config.getOntologyRequestHandler());
		
		LOGGER.trace("Ontology search URL: {}", getQueryUrl(query, config.getOntologyUrl()));
		
		QueryResponse response = server.query(query);
		List<OntologyEntryBean> annotations = response.getBeans(OntologyEntryBean.class);
		results = new ResultsList<>(annotations, rows, (start / rows), response.getResults().getNumFound());
	} catch (SolrServerException e) {
		throw new SearchEngineException(e);
	}
	
	return results;
}
 
Example 15
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 16
Source File: SolrController.java    From Spring-Boot-Book with Apache License 2.0 4 votes vote down vote up
@RequestMapping("/queryAll")
    public Object queryAll() throws IOException, SolrServerException {


        //第二种方式
        SolrQuery solrQuery = new SolrQuery();
        // 设置默认搜索域
        solrQuery.setQuery("*:*");
//        solrQuery.addField("*");
        solrQuery.set("q", "知然");
        solrQuery.add("q", "name:然");
        // 设置返回结果的排序规则
        solrQuery.setSort("id", SolrQuery.ORDER.asc);
        //设置查询的条数
        solrQuery.setRows(50);
        //设置查询的开始
        solrQuery.setStart(0);
        // 设置分页参数
        solrQuery.setStart(0);
        solrQuery.setRows(20);
        //设置高亮
        solrQuery.setHighlight(true);
        //设置高亮的字段
        solrQuery.addHighlightField("name");
        //设置高亮的样式
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");
        System.out.println(solrQuery);
        QueryResponse response = solrClient.query(solrQuery);
        //返回高亮显示结果
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        //response.getResults();查询返回的结果

        SolrDocumentList documentList = response.getResults();
        long numFound = documentList.getNumFound();
        System.out.println("总共查询到的文档数量: " + numFound);
        for (SolrDocument solrDocument : documentList) {
            System.out.println("solrDocument==============" + solrDocument);
            System.out.println("solrDocument==============" + solrDocument.get("name"));
        }
        return highlighting;
    }
 
Example 17
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);
}
 
Example 18
Source File: SolrDocumentSearch.java    From BioSolr with Apache License 2.0 4 votes vote down vote up
@Override
public ResultsList<Document> searchDocuments(String term, int start, int rows, List<String> additionalFields,
		List<String> filters, FacetStyle facetStyle) throws SearchEngineException {
	ResultsList<Document> results = null;

	try {
		SolrQuery query = new SolrQuery(term);
		query.setStart(start);
		query.setRows(rows);
		query.setRequestHandler(config.getDocumentRequestHandler());
		List<String> queryFields = new ArrayList<>(DEFAULT_SEARCH_FIELDS);
		if (additionalFields != null) {
			queryFields.addAll(additionalFields);
		}
		if (filters != null) {
			query.addFilterQuery(filters.toArray(new String[0]));
		}
		query.setParam(DisMaxParams.QF, queryFields.toArray(new String[queryFields.size()]));
		
		if (facetStyle == FacetStyle.NONE) {
			query.addFacetField(config.getFacetFields().toArray(new String[config.getFacetFields().size()]));
		} else {
			// Add the facet tree params
			query.setFacet(true);
			query.setParam("facet.tree", true);
			query.setParam("facet.tree.field", buildFacetTreeQueryParameter(facetStyle));
		}
		
		LOGGER.debug("Query: {}", query);

		QueryResponse response = server.query(query);
		List<Document> docs;
		long total = 0;
		
		if (response.getGroupResponse() != null) {
			docs = new ArrayList<>(rows);
			GroupResponse gResponse = response.getGroupResponse();
			for (GroupCommand gCommand : gResponse.getValues()) {
				total += gCommand.getNGroups();
				for (Group group : gCommand.getValues()) {
					docs.addAll(server.getBinder().getBeans(Document.class, group.getResult()));
				}
			}
		} else if (response.getResults().getNumFound() == 0) {
			docs = new ArrayList<>();
		} else {
			docs = response.getBeans(Document.class);
			total = response.getResults().getNumFound();
		}
		
		results = new ResultsList<>(docs, start, (start / rows), total, extractFacets(response, facetStyle));
	} catch (SolrServerException e) {
		throw new SearchEngineException(e);
	}

	return results;
}
 
Example 19
Source File: SolrDocumentSearch.java    From BioSolr with Apache License 2.0 4 votes vote down vote up
@Override
public ResultsList<Document> searchDocuments(String term, int start, int rows, List<String> additionalFields,
		List<String> filters) throws SearchEngineException {
	ResultsList<Document> results;

	try {
		SolrQuery query = new SolrQuery(term);
		query.setStart(start);
		query.setRows(rows);
		query.setRequestHandler(config.getDocumentRequestHandler());
		List<String> queryFields = new ArrayList<>(DEFAULT_SEARCH_FIELDS);
		if (additionalFields != null) {
			queryFields.addAll(additionalFields);
		}
		if (filters != null) {
			query.addFilterQuery(filters.toArray(new String[filters.size()]));
		}
		query.setParam(DisMaxParams.QF, queryFields.toArray(new String[queryFields.size()]));
		
		LOGGER.debug("Query: {}", query);

		QueryResponse response = server.query(query);
		List<Document> docs;
		long total = 0;
		
		if (response.getGroupResponse() != null) {
			docs = new ArrayList<>(rows);
			GroupResponse gResponse = response.getGroupResponse();
			for (GroupCommand gCommand : gResponse.getValues()) {
				total += gCommand.getNGroups();
				for (Group group : gCommand.getValues()) {
					docs.addAll(server.getBinder().getBeans(Document.class, group.getResult()));
				}
			}
		} else if (response.getResults().getNumFound() == 0) {
			docs = new ArrayList<>();
		} else {
			docs = response.getBeans(Document.class);
			total = response.getResults().getNumFound();
		}
		
		results = new ResultsList<>(docs, start, (start / rows), total);
	} catch (SolrServerException | IOException e) {
		throw new SearchEngineException(e);
	}

	return results;
}
 
Example 20
Source File: SolrControllerTest.java    From Spring-Boot-Book with Apache License 2.0 4 votes vote down vote up
@Test
    public void queryAll() throws IOException, SolrServerException {


        //第二种方式
        SolrQuery solrQuery = new SolrQuery();
        // 设置默认搜索域
        solrQuery.setQuery("*:*");
//        solrQuery.addField("*");
        solrQuery.set("q", "知然");
        solrQuery.add("q", "name:然");
        // 设置返回结果的排序规则
        solrQuery.setSort("id", SolrQuery.ORDER.asc);
        //设置查询的条数
        solrQuery.setRows(50);
        //设置查询的开始
        solrQuery.setStart(0);
        // 设置分页参数
        solrQuery.setStart(0);
        solrQuery.setRows(20);
        //设置高亮
        solrQuery.setHighlight(true);
        //设置高亮的字段
        solrQuery.addHighlightField("name");
        //设置高亮的样式
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");
        System.out.println(solrQuery);
        QueryResponse response = solrClient.query(solrQuery);
        //返回高亮显示结果
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        //response.getResults();查询返回的结果

        SolrDocumentList documentList = response.getResults();
        long numFound = documentList.getNumFound();
        System.out.println("总共查询到的文档数量: " + numFound);
        for (SolrDocument solrDocument : documentList) {
            System.out.println(solrDocument);
            System.out.println(solrDocument.get("name"));
        }
        System.out.println(highlighting);
    }