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

The following examples show how to use org.apache.solr.client.solrj.SolrQuery#setRequestHandler() . 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: MCROAIQuerySetResolver.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private SolrQuery getQuery() {
    SolrQuery solrQuery = new SolrQuery();
    // query
    String idQuery = getResult().stream()
        .map(getIdentifier())
        .map(MCRSolrUtils::escapeSearchValue)
        .collect(Collectors.joining(" OR ", "id:(", ")"));
    solrQuery.setQuery(idQuery);
    solrQuery.setFilterQueries(query);
    solrQuery.setFields("id");
    solrQuery.setRows(getResult().size());
    // request handler
    solrQuery.setRequestHandler(
        MCRConfiguration2.getString(getConfigPrefix() + "Search.RequestHandler").orElse("/select"));
    return solrQuery;
}
 
Example 2
Source File: SolrDocumentSearch.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@Override
public ResultsList<Document> searchByEfoUri(int start, int rows, String term, String... uris) throws SearchEngineException {
	ResultsList<Document> results = null;

	try {
		SolrQuery query = new SolrQuery(term + " OR " + EFO_URI_FIELD + ":" + buildUriFilter(uris));
		// query.addFilterQuery(EFO_URI_FIELD + ":" + buildUriFilter(uris));
		query.setStart(start);
		query.setRows(rows);
		query.setRequestHandler(config.getDocumentUriRequestHandler());

		LOGGER.debug("Solr query: {}", query);

		QueryResponse response = server.query(query);
		List<Document> docs = response.getBeans(Document.class);
		results = new ResultsList<>(docs, start, (start / rows), response.getResults().getNumFound());
	} catch (SolrServerException e) {
		throw new SearchEngineException(e);
	}

	return results;
}
 
Example 3
Source File: SolrOntologySearch.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@Override
public OntologyEntryBean findOntologyEntryByUri(String uri) throws SearchEngineException {
	OntologyEntryBean retVal = null;
	
	try {
		SolrQuery query = new SolrQuery(uri);
		query.setRequestHandler(config.getOntologyNodeRequestHandler());
		
		QueryResponse response = server.query(query);
		List<OntologyEntryBean> annotations = response.getBeans(OntologyEntryBean.class);
		if (annotations.size() > 0) {
			retVal = annotations.get(0);
		}
	} catch (SolrServerException e) {
		throw new SearchEngineException(e);
	}
	
	return retVal;
}
 
Example 4
Source File: ItemSearchServiceLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSearchingWithIncompleteKeyword_thenKeywordSuggestionsShouldBeReturned() throws Exception {
    itemSearchService.index("hm0001", "Brand1 Washing Machine", "Home Appliances", 100f);
    itemSearchService.index("hm0002", "Brand1 Refrigerator", "Home Appliances", 300f);
    itemSearchService.index("hm0003", "Brand2 Ceiling Fan", "Home Appliances", 200f);
    itemSearchService.index("hm0004", "Brand2 Dishwasher", "Home washing equipments", 250f);

    SolrQuery query = new SolrQuery();
    query.setRequestHandler("/suggest");
    query.set("suggest", "true");
    query.set("suggest.build", "true");
    query.set("suggest.dictionary", "mySuggester");
    query.set("suggest.q", "Hom");
    QueryResponse response = solrClient.query(query);

    SuggesterResponse suggesterResponse = response.getSuggesterResponse();
    Map<String, List<String>> suggestedTerms = suggesterResponse.getSuggestedTerms();
    List<String> suggestions = suggestedTerms.get("mySuggester");

    assertEquals(2, suggestions.size());

    for (String term : suggestions) {
        if (!"Home Appliances".equals(term) && !"Home washing equipments".equals(term)) {
            fail("Unexpected suggestions");
        }
    }

}
 
Example 5
Source File: MCROAISolrSearcher.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private SolrQuery getBaseQuery(String restrictionField) {
    String configPrefix = this.identify.getConfigPrefix();
    SolrQuery query = new SolrQuery();
    // query
    MCRConfiguration2.getString(configPrefix + "Search.Restriction")
        .ifPresent(restriction -> query.set(restrictionField, restriction));
    String[] requiredFields = Stream.concat(Stream.of("id", getModifiedField()), getRequiredFieldNames().stream())
        .toArray(String[]::new);
    query.setFields(requiredFields);
    // request handler
    query.setRequestHandler(MCRConfiguration2.getString(configPrefix + "Search.RequestHandler").orElse("/select"));
    return query;
}
 
Example 6
Source File: TermsResponseTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testTermsResponse() throws Exception {
  SolrInputDocument doc = new SolrInputDocument();
  doc.setField("id", 1);
  doc.setField("terms_s", "samsung");
  getSolrClient().add(doc);
  getSolrClient().commit(true, true);

  SolrQuery query = new SolrQuery();
  query.setRequestHandler("/terms");
  query.setTerms(true);
  query.setTermsLimit(5);
  query.setTermsLower("s");
  query.setTermsPrefix("s");
  query.addTermsField("terms_s");
  query.setTermsMinCount(1);

  QueryRequest request = new QueryRequest(query);
  List<Term> terms = request.process(getSolrClient()).getTermsResponse().getTerms("terms_s");

  Assert.assertNotNull(terms);
  Assert.assertEquals(terms.size(), 1);

  Term term = terms.get(0);
  Assert.assertEquals(term.getTerm(), "samsung");
  Assert.assertEquals(term.getFrequency(), 1);
}
 
Example 7
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 8
Source File: GetSolr.java    From nifi with Apache License 2.0 5 votes vote down vote up
private String getFieldNameOfUniqueKey() {
    final SolrQuery solrQuery = new SolrQuery();
    try {
        solrQuery.setRequestHandler("/schema/uniquekey");
        final QueryRequest req = new QueryRequest(solrQuery);
        if (isBasicAuthEnabled()) {
            req.setBasicAuthCredentials(getUsername(), getPassword());
        }

        return(req.process(getSolrClient()).getResponse().get("uniqueKey").toString());
    } catch (SolrServerException | IOException e) {
        getLogger().error("Solr query to retrieve uniqueKey-field failed due to {}", new Object[]{solrQuery.toString(), e}, e);
        throw new ProcessException(e);
    }
}
 
Example 9
Source File: SolrServersITCase.java    From apache-solr-essentials with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that records have been effectively indexed.
 * 
 * @throws SolrServerException in case of Solr communication failure.
 */
void verify() throws SolrServerException {
	final SolrQuery query = new SolrQuery("*:*");
	query.setRequestHandler("/h1");
	
	final QueryResponse response = solr.query(query);
	assertEquals(sampleData().size(), (int)response.getResults().getNumFound());
}
 
Example 10
Source File: SearchITCase.java    From apache-solr-essentials with Apache License 2.0 5 votes vote down vote up
/**
 * Illustrates how to execute a query with a response callback.
 * 
 * @throws Exception hopefully never, otherwise the test fails.
 */
@Test
public void withCallback() throws Exception {
	final int expectedWindowSize = 2;
	
	// 1. Prepare the Query object
	// The query string can be directly injected in the constructor. 
	// Note that the /h2 request handler uses a dismax query parser and 
	// therefore the query string is composed by just search term (no fields).
	final SolrQuery query = new SolrQuery("rock jazz");
	query.setRequestHandler("/h2");
	query.setFacet(false);
	query.setRows(expectedWindowSize);
	
	// 2. creates a callback handler
	final SampleStreamingResponseCallback callbackHandler = new SampleStreamingResponseCallback(4);
	
	// 3. Note that in this case we are not invoking "query" but "queryAndStreamResponse"
	// That requires the callback handler previously defined. 
	// That method still returns a QueryResponse but, as its javadoc says, 
	// it is not supposed to be used because streamed documents are removed from there.
	@SuppressWarnings("unused")
	final QueryResponse dontUseMe = SEARCHER.queryAndStreamResponse(query, callbackHandler);
	
	// 4. Assert window result
	assertEquals(expectedWindowSize, callbackHandler.getCurrentWindowSize());
}
 
Example 11
Source File: SearchITCase.java    From apache-solr-essentials with Apache License 2.0 5 votes vote down vote up
/**
 * Selects all documents using an handler configured with SolrQueryParser
 * 
 * @throws Exception hopefully never, otherwise the test fails.
 */
@Test
public void selectAll() throws Exception {
	// 1. Prepare the Query object
	// The query string can be directly injected in the constructor
	final SolrQuery query = new SolrQuery("*:*");
	query.setRequestHandler("/h1");
	
	// These settings will override the "defaults" section
	query.setFacet(false);
	query.setHighlight(false);
	query.setSort("released", ORDER.desc);
	
	// We are asking 5 documents per page
	query.setRows(5);
	
	// 2. Send the query request and get the corresponding response.
	final QueryResponse response = SEARCHER.query(query);
	
	// 3. Get the result object, containing documents and metadata.
	final SolrDocumentList documents = response.getResults();
	
	// If not explicitly requested (or set in the handler) the start is set to 0
	assertEquals(0, documents.getStart());
	
	// Total number of documents found must be equals to all documents we previously indexed
	assertEquals(sampleData().size(), documents.getNumFound());
	
	// Page size must be 5, as requested
	assertEquals(5, documents.size());
}
 
Example 12
Source File: ServiceSolrClient.java    From ranger with Apache License 2.0 5 votes vote down vote up
public List<String> getFieldList(String collection,
		List<String> ignoreFieldList) throws Exception {
	// TODO: Best is to get the collections based on the collection value
	// which could contain wild cards
	String queryStr = "";
	if (collection != null && !collection.isEmpty()) {
		queryStr += "/" + collection;
	}
	queryStr += "/schema/fields";
	SolrQuery query = new SolrQuery();
	query.setRequestHandler(queryStr);
	QueryRequest req = new QueryRequest(query);
	String decPassword = getDecryptedPassword();
	if (username != null && decPassword != null) {
	    req.setBasicAuthCredentials(username, decPassword);
	}
	QueryResponse response = req.process(solrClient);

	List<String> fieldList = new ArrayList<String>();
	if (response != null && response.getStatus() == 0) {
		@SuppressWarnings("unchecked")
		List<SimpleOrderedMap<String>> fields = (ArrayList<SimpleOrderedMap<String>>) response
				.getResponse().get("fields");
		for (SimpleOrderedMap<String> fmap : fields) {
			String fieldName = fmap.get("name");
			if (ignoreFieldList == null
					|| !ignoreFieldList.contains(fieldName)) {
				fieldList.add(fieldName);
			}
		}
	} else {
		LOG.error("Error getting fields for collection=" + collection
				+ ", response=" + response);
	}
	return fieldList;
}
 
Example 13
Source File: SystemService.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Performs Solr restoration.
 *
 * @param properties properties containing arguments to execute the restoration.
 */
private static void restoreSolr5Index (Properties properties) throws
      IOException, SolrServerException
{
   String solrHome = properties.getProperty ("dhus.solr.home");
   String coreName = properties.getProperty ("dhus.solr.core.name");
   final String name = properties.getProperty ("dhus.solr.backup.name");
   final String location = properties.getProperty (
         "dhus.solr.backup.location");

   if (solrHome == null || coreName == null || name == null ||
       location == null)
   {
      throw new UnsupportedOperationException ();
   }

   System.setProperty ("solr.solr.home", solrHome);
   CoreContainer core = new CoreContainer (solrHome);
   EmbeddedSolrServer server = new EmbeddedSolrServer (core, coreName);
   try
   {
      server.getCoreContainer ().load ();

      SolrQuery query = new SolrQuery();
      query.setRequestHandler("/replication");
      query.set("command", "restore");
      query.set("name", name);
      query.set("location", location);

      server.query(query);
      LOGGER.info("SolR indexes restored.");
   }
   finally
   {
      server.close();
   }
   
}
 
Example 14
Source File: SolrDao.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Get suggestions from the suggester component.
 * @param input analysed by the suggester component.
 * @return the suggester component response.
 * @throws IOException network error.
 * @throws SolrServerException solr error.
 */
public SuggesterResponse getSuggestions(String input) throws IOException, SolrServerException
{
   SolrQuery query = new SolrQuery(input);
   query.setRequestHandler("/suggest");

   return search(query).getSuggesterResponse();
}
 
Example 15
Source File: TestTlogReplica.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private void checkRTG(int from, int to, List<JettySolrRunner> solrRunners) throws Exception{
  for (JettySolrRunner solrRunner: solrRunners) {
    try (SolrClient client = solrRunner.newClient()) {
      for (int i = from; i <= to; i++) {
        SolrQuery query = new SolrQuery();
        query.set("distrib", false);
        query.setRequestHandler("/get");
        query.set("id",i);
        QueryResponse res = client.query(collectionName, query);
        assertNotNull("Can not find doc "+ i + " in " + solrRunner.getBaseUrl(),res.getResponse().get("doc"));
      }
    }
  }
}
 
Example 16
Source File: SearchITCase.java    From apache-solr-essentials with Apache License 2.0 4 votes vote down vote up
/**
 * Demonstrates how to ask for faceting and iterate over response facets.
 * 
 * @throws Exception hopefully never, otherwise the test fails.
 */
@Test
public void facets() throws Exception {
	// 1. Prepare the Query object
	// The query string can be directly injected in the constructor
	final SolrQuery query = new SolrQuery("*:*");
	query.setRequestHandler("/h1");
	
	// These settings will override the "defaults" section
	// Note that this handler sets facet to true, so the following line is
	// not actually needed
	query.setFacet(true);
	query.addFacetField("genre", "released");
	
	// We don't want highlighting here
	// Since the HL component is disabled by default, also this line is not needed.
	query.setHighlight(false);
	
	// We are only interested in facets, so skip don't include any 
	// document in the response.
	query.setRows(0);
	
	// 2. Send the query request and get the corresponding response.
	final QueryResponse response = SEARCHER.query(query);
	
	// 3. Get the result object, containing documents and metadata.
	final SolrDocumentList documents = response.getResults();
	
	// If not explicitly requested (or set in the handler) the start is set to 0
	assertEquals(0, documents.getStart());
	
	// Total number of documents found must be equals to all documents we previously indexed
	assertEquals(sampleData().size(), documents.getNumFound());
	
	// Page size must be 0, as requested
	assertEquals(0, documents.size());
	
	final FacetField genre = response.getFacetField("genre");
	assertNotNull(genre);
	 
	// This is something that should never appear within a TestCase :) 
	// however is useful to demonstrate how to iterate over facet values
	for (final Count count : genre.getValues()) {
		// e.g. Jazz : 19
		// e.g. Fusion: 11
		System.out.println(count.getName() + " : " + count.getCount());
	}
}
 
Example 17
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 18
Source File: MergingSolrSpewer.java    From extract with MIT License 4 votes vote down vote up
private void merge(final TikaDocument tikaDocument, final SolrInputDocument inputDocument) throws IOException,
		SolrServerException {
	final SolrDocument existingDocument;
	final SolrQuery params = new SolrQuery();
	final String resourceNameKey = fields.forMetadata(Metadata.RESOURCE_NAME_KEY);

	// The tikaDocument must be retrieved from the real-time-get (RTG) handler, otherwise we'd have to commit every
	// time a tikaDocument is added.
	params.setRequestHandler("/get");

	// Request only the fields which must be merged, not the entire tikaDocument.
	params.setFields(fields.forPath(), fields.forParentPath(), fields.forVersion(), resourceNameKey);
	existingDocument = client.getById(tikaDocument.getId(), params);

	// Since we're updating the path and parent path values of an existing tikaDocument, set the version field to
	// avoid conflicts. Note that child documents don't have a version field.
	if (null != existingDocument) {
		final Object version = existingDocument.getFieldValue(fields.forVersion());
		if (null != version) {
			inputDocument.setField(fields.forVersion(), version);
		}

	} else {
		inputDocument.setField(fields.forVersion(), "-1");
	}

	// Set the path field.
	if (null != fields.forPath()) {
		mergeField(fields.forPath(), tikaDocument.getPath().toString(), existingDocument, inputDocument);
	}

	// Set the parent path field.
	if (null != fields.forParentPath() && tikaDocument.getPath().getNameCount() > 1) {
		mergeField(fields.forParentPath(), tikaDocument.getPath().getParent().toString(), existingDocument,
				inputDocument);
	}

	// Merge the resource name field.
	if (tikaDocument.getMetadata() != null) {
		mergeField(resourceNameKey, tikaDocument.getMetadata().get(Metadata.RESOURCE_NAME_KEY), existingDocument,
				inputDocument);
	}
}
 
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, 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 20
Source File: SolrEntityProcessor.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
protected QueryResponse doQuery() {
  SolrEntityProcessor.this.queryString = context.getResolvedEntityAttribute(QUERY);
  if (SolrEntityProcessor.this.queryString == null) {
    throw new DataImportHandlerException(
        DataImportHandlerException.SEVERE,
        "SolrEntityProcessor: parameter 'query' is required"
    );
  }

  String rowsP = context.getResolvedEntityAttribute(CommonParams.ROWS);
  if (rowsP != null) {
    rows = Integer.parseInt(rowsP);
  }

  String sortParam = context.getResolvedEntityAttribute(CommonParams.SORT);
  
  String fqAsString = context.getResolvedEntityAttribute(CommonParams.FQ);
  if (fqAsString != null) {
    SolrEntityProcessor.this.filterQueries = fqAsString.split(",");
  }

  String fieldsAsString = context.getResolvedEntityAttribute(CommonParams.FL);
  if (fieldsAsString != null) {
    SolrEntityProcessor.this.fields = fieldsAsString.split(",");
  }
  SolrEntityProcessor.this.requestHandler = context.getResolvedEntityAttribute(CommonParams.QT);
 

  SolrQuery solrQuery = new SolrQuery(queryString);
  solrQuery.setRows(rows);
  
  if (sortParam!=null) {
    solrQuery.setParam(CommonParams.SORT, sortParam);
  }
  
  passNextPage(solrQuery);
  
  if (fields != null) {
    for (String field : fields) {
      solrQuery.addField(field);
    }
  }
  solrQuery.setRequestHandler(requestHandler);
  solrQuery.setFilterQueries(filterQueries);
  
  
  QueryResponse response = null;
  try {
    response = solrClient.query(solrQuery);
  } catch (SolrServerException | IOException | SolrException e) {
    if (ABORT.equals(onError)) {
      wrapAndThrow(SEVERE, e);
    } else if (SKIP.equals(onError)) {
      wrapAndThrow(DataImportHandlerException.SKIP_ROW, e);
    }
  }
  
  if (response != null) {
    SolrEntityProcessor.this.rowIterator = createNextPageIterator(response);
  }
  return response;
}