Java Code Examples for org.apache.solr.client.solrj.SolrQuery#addField()
The following examples show how to use
org.apache.solr.client.solrj.SolrQuery#addField() .
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: SolrTest.java From parker with MIT License | 6 votes |
@Test public void testQuery() throws Exception { SolrQuery query = new SolrQuery(); // 根据标题或内容来搜索 query.setQuery("title:项目 or content:项目"); // 返回的字段 query.addField("id"); query.addField("title"); query.addField("content"); QueryResponse response = client.query(query); SolrDocumentList documents = response.getResults(); System.out.println("结果集大小=" + documents.size()); for(SolrDocument document : documents) { final String title = (String) document.getFirstValue("title"); System.out.println(title); //final String name = (String) document.getFirstValue("name"); //System.out.println("id: " + id + "; name: " + name); } }
Example 2
Source File: SolrFilterVisitor.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
public void apply(SolrQuery solrQuery, Filter filter) { visit(filter); solrQuery.addFilterQuery(queryBuilder.toString()); List<LikeFilter> likeFilters = extractLikeFilters(filter); if (!likeFilters.isEmpty()) { solrQuery.addField("id"); solrQuery.setHighlight(true); solrQuery.setHighlightFragsize(0); solrQuery.add("hl.q", "*" + likeFilters.get(0).getValue() + "*"); for (LikeFilter likeFilter : likeFilters) { String fieldName = likeFilter.getProjection().getName(); if(highlightFields.contains(fieldName)) { solrQuery.addHighlightField(fieldName); } } } }
Example 3
Source File: UsingSolrJRefGuideExamplesTest.java From lucene-solr with Apache License 2.0 | 6 votes |
@Test public void queryBeanValueTypeExample() throws Exception { expectLine("Found 3 documents"); expectLine("id: 1; name: Fitbit Alta"); expectLine("id: 2; name: Sony Walkman"); expectLine("id: 3; name: Garmin GPS"); // tag::solrj-query-bean-value-type[] final SolrClient client = getSolrClient(); final SolrQuery query = new SolrQuery("*:*"); query.addField("id"); query.addField("name"); query.setSort("id", ORDER.asc); final QueryResponse response = client.query("techproducts", query); final List<TechProduct> products = response.getBeans(TechProduct.class); // end::solrj-query-bean-value-type[] print("Found " + products.size() + " documents"); for (TechProduct product : products) { print("id: " + product.id + "; name: " + product.name); } }
Example 4
Source File: BasicDistributedZkTest.java From lucene-solr with Apache License 2.0 | 6 votes |
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 5
Source File: UsingSolrJRefGuideExamplesTest.java From lucene-solr with Apache License 2.0 | 5 votes |
@Test public void queryWithSolrQueryExample() throws Exception { final int numResultsToReturn = 3; expectLine("Found 3 documents"); expectLine("id: 1; name: Fitbit Alta"); expectLine("id: 2; name: Sony Walkman"); expectLine("id: 3; name: Garmin GPS"); final SolrClient client = getSolrClient(); // tag::solrj-query-with-solrquery[] final SolrQuery query = new SolrQuery("*:*"); query.addField("id"); query.addField("name"); query.setSort("id", ORDER.asc); query.setRows(numResultsToReturn); // end::solrj-query-with-solrquery[] final QueryResponse response = client.query("techproducts", query); final SolrDocumentList documents = response.getResults(); print("Found " + documents.getNumFound() + " documents"); assertEquals(numResultsToReturn, documents.size()); for(SolrDocument document : documents) { final String id = (String) document.getFirstValue("id"); final String name = (String) document.getFirstValue("name"); print("id: "+ id + "; name: " + name); } }
Example 6
Source File: DistributedDebugComponentTest.java From lucene-solr with Apache License 2.0 | 5 votes |
@Test // commented out on: 24-Dec-2018 @BadApple(bugUrl="https://issues.apache.org/jira/browse/SOLR-12028") // added 20-Sep-2018 public void testCompareWithNonDistributedRequest() throws SolrServerException, IOException { SolrQuery query = new SolrQuery(); query.setQuery("id:1 OR id:2"); query.setFilterQueries("id:[0 TO 10]", "id:[0 TO 5]"); query.setRows(1); query.setSort("id", SolrQuery.ORDER.asc); // thus only return id:1 since rows 1 query.set("debug", "true"); query.set("distrib", "true"); query.setFields("id"); if (random().nextBoolean()) { // can affect rb.onePassDistributedQuery query.addField("text"); } query.set(ShardParams.DISTRIB_SINGLE_PASS, random().nextBoolean()); query.set("shards", shard1 + "," + shard2); QueryResponse distribResponse = collection1.query(query); // same query but not distributed query.set("distrib", "false"); query.remove("shards"); QueryResponse nonDistribResponse = collection1.query(query); assertNotNull(distribResponse.getDebugMap().get("track")); assertNull(nonDistribResponse.getDebugMap().get("track")); assertEquals(distribResponse.getDebugMap().size() - 1, nonDistribResponse.getDebugMap().size()); assertSectionEquals(distribResponse, nonDistribResponse, "explain"); assertSectionEquals(distribResponse, nonDistribResponse, "rawquerystring"); assertSectionEquals(distribResponse, nonDistribResponse, "querystring"); assertSectionEquals(distribResponse, nonDistribResponse, "parsedquery"); assertSectionEquals(distribResponse, nonDistribResponse, "parsedquery_toString"); assertSectionEquals(distribResponse, nonDistribResponse, "QParser"); assertSectionEquals(distribResponse, nonDistribResponse, "filter_queries"); assertSectionEquals(distribResponse, nonDistribResponse, "parsed_filter_queries"); // timing should have the same sections: assertSameKeys((NamedList<?>)nonDistribResponse.getDebugMap().get("timing"), (NamedList<?>)distribResponse.getDebugMap().get("timing")); }
Example 7
Source File: SolrIndex.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override protected Iterable<? extends DocumentDistance> geoQuery(IRI geoProperty, Point p, final IRI units, double distance, String distanceVar, Var contextVar) throws MalformedQueryException, IOException { double kms = GeoUnits.toKilometres(distance, units); String qstr = "{!geofilt score=recipDistance}"; if (contextVar != null) { Resource ctx = (Resource) contextVar.getValue(); String tq = termQuery(SearchFields.CONTEXT_FIELD_NAME, SearchFields.getContextID(ctx)); if (ctx != null) { qstr = tq + " AND " + qstr; } else { qstr = "-" + tq + " AND " + qstr; } } SolrQuery q = new SolrQuery(qstr); q.set(SpatialParams.FIELD, SearchFields.getPropertyField(geoProperty)); q.set(SpatialParams.POINT, p.getY() + "," + p.getX()); q.set(SpatialParams.DISTANCE, Double.toString(kms)); q.addField(SearchFields.URI_FIELD_NAME); // ':' is part of the fl parameter syntax so we can't use the full // property field name // instead we use wildcard + local part of the property URI q.addField("*" + geoProperty.getLocalName()); // always include the distance - needed for sanity checking q.addField(DISTANCE_FIELD + ":geodist()"); boolean requireContext = (contextVar != null && !contextVar.hasValue()); if (requireContext) { q.addField(SearchFields.CONTEXT_FIELD_NAME); } QueryResponse response; try { response = search(q); } catch (SolrServerException e) { throw new IOException(e); } SolrDocumentList results = response.getResults(); return Iterables.transform(results, (SolrDocument document) -> { SolrSearchDocument doc = new SolrSearchDocument(document); return new SolrDocumentDistance(doc, units); }); }
Example 8
Source File: SolrIndex.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
@Override protected Iterable<? extends DocumentResult> geoRelationQuery(String relation, IRI geoProperty, Shape shape, Var contextVar) throws MalformedQueryException, IOException { String spatialOp = toSpatialOp(relation); if (spatialOp == null) { return null; } String wkt = toWkt(shape); String qstr = "\"" + spatialOp + "(" + wkt + ")\""; if (contextVar != null) { Resource ctx = (Resource) contextVar.getValue(); String tq = termQuery(SearchFields.CONTEXT_FIELD_NAME, SearchFields.getContextID(ctx)); if (ctx != null) { qstr = tq + " AND " + qstr; } else { qstr = "-" + tq + " AND " + qstr; } } SolrQuery q = new SolrQuery(qstr); q.set(CommonParams.DF, SearchFields.getPropertyField(geoProperty)); q.addField(SearchFields.URI_FIELD_NAME); // ':' is part of the fl parameter syntax so we can't use the full // property field name // instead we use wildcard + local part of the property URI q.addField("*" + geoProperty.getLocalName()); boolean requireContext = (contextVar != null && !contextVar.hasValue()); if (requireContext) { q.addField(SearchFields.CONTEXT_FIELD_NAME); } QueryResponse response; try { response = search(q); } catch (SolrServerException e) { throw new IOException(e); } SolrDocumentList results = response.getResults(); return Iterables.transform(results, (SolrDocument document) -> { SolrSearchDocument doc = new SolrSearchDocument(document); return new SolrDocumentResult(doc); }); }
Example 9
Source File: SolrExampleStreamingBinaryHttp2Test.java From lucene-solr with Apache License 2.0 | 4 votes |
@Test public void testQueryAndStreamResponse() throws Exception { // index a simple document with one child SolrClient client = getSolrClient(); client.deleteByQuery("*:*"); SolrInputDocument child = new SolrInputDocument(); child.addField("id", "child"); child.addField("type_s", "child"); child.addField("text_s", "text"); SolrInputDocument parent = new SolrInputDocument(); parent.addField("id", "parent"); parent.addField("type_s", "parent"); parent.addChildDocument(child); client.add(parent); client.commit(); // create a query with child doc transformer SolrQuery query = new SolrQuery("{!parent which='type_s:parent'}text_s:text"); query.addField("*,[child parentFilter='type_s:parent']"); // test regular query QueryResponse response = client.query(query); assertEquals(1, response.getResults().size()); SolrDocument parentDoc = response.getResults().get(0); assertEquals(1, parentDoc.getChildDocumentCount()); // test streaming final List<SolrDocument> docs = new ArrayList<>(); client.queryAndStreamResponse(query, new StreamingResponseCallback() { @Override public void streamSolrDocument(SolrDocument doc) { docs.add(doc); } @Override public void streamDocListInfo(long numFound, long start, Float maxScore) { } }); assertEquals(1, docs.size()); parentDoc = docs.get(0); assertEquals(1, parentDoc.getChildDocumentCount()); }
Example 10
Source File: SolrExampleStreamingBinaryTest.java From lucene-solr with Apache License 2.0 | 4 votes |
@Test public void testQueryAndStreamResponse() throws Exception { // index a simple document with one child SolrClient client = getSolrClient(); client.deleteByQuery("*:*"); SolrInputDocument child = new SolrInputDocument(); child.addField("id", "child"); child.addField("type_s", "child"); child.addField("text_s", "text"); SolrInputDocument parent = new SolrInputDocument(); parent.addField("id", "parent"); parent.addField("type_s", "parent"); parent.addChildDocument(child); client.add(parent); client.commit(); // create a query with child doc transformer SolrQuery query = new SolrQuery("{!parent which='type_s:parent'}text_s:text"); query.addField("*,[child parentFilter='type_s:parent']"); // test regular query QueryResponse response = client.query(query); assertEquals(1, response.getResults().size()); SolrDocument parentDoc = response.getResults().get(0); assertEquals(1, parentDoc.getChildDocumentCount()); // test streaming final List<SolrDocument> docs = new ArrayList<>(); client.queryAndStreamResponse(query, new StreamingResponseCallback() { @Override public void streamSolrDocument(SolrDocument doc) { docs.add(doc); } @Override public void streamDocListInfo(long numFound, long start, Float maxScore) { } }); assertEquals(1, docs.size()); parentDoc = docs.get(0); assertEquals(1, parentDoc.getChildDocumentCount()); }
Example 11
Source File: SolrEntityProcessor.java From lucene-solr with Apache License 2.0 | 4 votes |
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; }
Example 12
Source File: TestTolerantSearch.java From lucene-solr with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") public void testGetFieldsPhaseError() throws SolrServerException, IOException { BadResponseWriter.failOnGetFields = true; BadResponseWriter.failOnGetTopIds = false; SolrQuery query = new SolrQuery(); query.setQuery("subject:batman OR subject:superman"); query.addField("id"); query.addField("subject"); query.set("distrib", "true"); query.set("shards", shard1 + "," + shard2); query.set(ShardParams.SHARDS_INFO, "true"); query.set("debug", "true"); query.set("stats", "true"); query.set("stats.field", "id"); query.set("mlt", "true"); query.set("mlt.fl", "title"); query.set("mlt.count", "1"); query.set("mlt.mintf", "0"); query.set("mlt.mindf", "0"); query.setHighlight(true); query.addFacetField("id"); query.setFacet(true); ignoreException("Dummy exception in BadResponseWriter"); expectThrows(SolrException.class, () -> collection1.query(query)); query.set(ShardParams.SHARDS_TOLERANT, "true"); QueryResponse response = collection1.query(query); assertTrue(response.getResponseHeader().getBooleanArg(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY)); NamedList<Object> shardsInfo = ((NamedList<Object>)response.getResponse().get(ShardParams.SHARDS_INFO)); boolean foundError = false; for (int i = 0; i < shardsInfo.size(); i++) { if (shardsInfo.getName(i).contains("collection2")) { assertNotNull(((NamedList<Object>)shardsInfo.getVal(i)).get("error")); foundError = true; break; } } assertTrue(foundError); assertEquals("1", response.getResults().get(0).getFieldValue("id")); assertEquals("batman", response.getResults().get(0).getFirstValue("subject")); unIgnoreException("Dummy exception in BadResponseWriter"); }
Example 13
Source File: TestTolerantSearch.java From lucene-solr with Apache License 2.0 | 4 votes |
@SuppressWarnings("unchecked") public void testGetTopIdsPhaseError() throws SolrServerException, IOException { BadResponseWriter.failOnGetTopIds = true; BadResponseWriter.failOnGetFields = false; SolrQuery query = new SolrQuery(); query.setQuery("subject:batman OR subject:superman"); query.addField("id"); query.addField("subject"); query.set("distrib", "true"); query.set("shards", shard1 + "," + shard2); query.set(ShardParams.SHARDS_INFO, "true"); query.set("debug", "true"); query.set("stats", "true"); query.set("stats.field", "id"); query.set("mlt", "true"); query.set("mlt.fl", "title"); query.set("mlt.count", "1"); query.set("mlt.mintf", "0"); query.set("mlt.mindf", "0"); query.setHighlight(true); query.addFacetField("id"); query.setFacet(true); ignoreException("Dummy exception in BadResponseWriter"); expectThrows(Exception.class, () -> collection1.query(query)); query.set(ShardParams.SHARDS_TOLERANT, "true"); QueryResponse response = collection1.query(query); assertTrue(response.getResponseHeader().getBooleanArg(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY)); NamedList<Object> shardsInfo = ((NamedList<Object>)response.getResponse().get(ShardParams.SHARDS_INFO)); boolean foundError = false; for (int i = 0; i < shardsInfo.size(); i++) { if (shardsInfo.getName(i).contains("collection2")) { assertNotNull(((NamedList<Object>)shardsInfo.getVal(i)).get("error")); foundError = true; break; } } assertTrue(foundError); assertFalse(""+response, response.getResults().isEmpty()); assertEquals("1", response.getResults().get(0).getFieldValue("id")); assertEquals("batman", response.getResults().get(0).getFirstValue("subject")); unIgnoreException("Dummy exception in BadResponseWriter"); }