Java Code Examples for org.apache.solr.common.SolrDocument#getFirstValue()

The following examples show how to use org.apache.solr.common.SolrDocument#getFirstValue() . 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 vote down vote up
@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: DistributedVersionInfoTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Query the real-time get handler for a specific doc by ID to verify it
 * exists in the provided server, using distrib=false so it doesn't route to another replica.
 */
@SuppressWarnings("rawtypes")
protected Long assertDocExists(HttpSolrClient solr, String coll, String docId, Long expVers) throws Exception {
  QueryRequest qr = new QueryRequest(params("qt", "/get", "id", docId, "distrib", "false", "fl", "id,_version_"));
  NamedList rsp = solr.request(qr);
  SolrDocument doc = (SolrDocument)rsp.get("doc");
  String match = JSONTestUtil.matchObj("/id", doc, docId);
  assertTrue("Doc with id=" + docId + " not found in " + solr.getBaseURL() +
      " due to: " + match + "; rsp=" + rsp, match == null);

  Long vers = (Long)doc.getFirstValue("_version_");
  assertNotNull(vers);
  if (expVers != null)
    assertEquals("expected version of doc "+docId+" to be "+expVers, expVers, vers);

  return vers;
}
 
Example 3
Source File: TestRandomFlRTGCloud.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public Collection<String> assertRTGResults(final Collection<FlValidator> validators,
                                           final SolrInputDocument expected,
                                           final SolrDocument actual) {
  final Object value =  actual.getFirstValue(resultKey);
  assertNotNull(getFlParam() + " => no value in actual doc", value);
  assertTrue(USAGE + " must be an Integer: " + value, value instanceof Integer);

  int minValidDocId = -1; // if it comes from update log
  for (FlValidator other : validators) {
    if (other.requiresRealtimeSearcherReOpen()) {
      minValidDocId = 0;
      break;
    }
  }
  assertTrue(USAGE + " must be >= " + minValidDocId + ": " + value,
             minValidDocId <= ((Integer)value).intValue());
  return Collections.<String>singleton(resultKey);
}
 
Example 4
Source File: TextIndexSolr5.java    From BioSolr with Apache License 2.0 6 votes vote down vote up
@Override
public List<TextHit> query(Node property, String qs, int limit) {
	SolrDocumentList solrResults = solrQuery(qs, limit) ;
	List<TextHit> results = new ArrayList<>() ;

	for ( SolrDocument sd : solrResults ) {
		String str = (String)sd.getFieldValue(docDef.getEntityField()) ;
		// log.info("Entity: "+uriStr) ;
		Node n = TextQueryFuncs.stringToNode(str) ;
		Float score = (Float) sd.getFirstValue("score");
		// capture literal value, if stored
		Node literal = null;
		String field = (property != null) ? docDef.getField(property) : docDef.getPrimaryField();
		String value = (String) sd.getFirstValue(field);
		if (value != null) {
			literal = NodeFactory.createLiteral(value); // FIXME: language and datatype
		}
		TextHit hit = new TextHit(n, score.floatValue(), literal);
		results.add(hit) ;
	}

	if ( limit > 0 && results.size() > limit )
		results = results.subList(0, limit) ;

	return results ;
}
 
Example 5
Source File: TestPutSolrContentStream.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that given SolrServer contains the expected SolrDocuments.
 */
private static void verifySolrDocuments(SolrClient solrServer, Collection<SolrDocument> expectedDocuments)
        throws IOException, SolrServerException {

    solrServer.commit();

    SolrQuery query = new SolrQuery("*:*");
    QueryResponse qResponse = solrServer.query(query);
    Assert.assertEquals(expectedDocuments.size(), qResponse.getResults().getNumFound());

    // verify documents have expected fields and values
    for (SolrDocument expectedDoc : expectedDocuments) {
        boolean found = false;
        for (SolrDocument solrDocument : qResponse.getResults()) {
            boolean foundAllFields = true;
            for (String expectedField : expectedDoc.getFieldNames()) {
                Object expectedVal = expectedDoc.getFirstValue(expectedField);
                Object actualVal = solrDocument.getFirstValue(expectedField);
                foundAllFields = expectedVal.equals(actualVal);
            }

            if (foundAllFields) {
                found = true;
                break;
            }
        }
        Assert.assertTrue("Could not find " + expectedDoc, found);
    }
}
 
Example 6
Source File: UsingSolrJRefGuideExamplesTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void queryWithRawSolrParamsExample() 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-with-raw-solrparams[]
  final SolrClient client = getSolrClient();

  final Map<String, String> queryParamMap = new HashMap<String, String>();
  queryParamMap.put("q", "*:*");
  queryParamMap.put("fl", "id, name");
  queryParamMap.put("sort", "id asc");
  MapSolrParams queryParams = new MapSolrParams(queryParamMap);

  final QueryResponse response = client.query("techproducts", queryParams);
  final SolrDocumentList documents = response.getResults();

  print("Found " + documents.getNumFound() + " documents");
  for(SolrDocument document : documents) {
    final String id = (String) document.getFirstValue("id");
    final String name = (String) document.getFirstValue("name");
    
    print("id: " + id + "; name: " + name);
  }
  // end::solrj-query-with-raw-solrparams[]
}
 
Example 7
Source File: UsingSolrJRefGuideExamplesTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@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 8
Source File: TestCustomDocTransformer.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static String getAsString(String field, SolrDocument doc) {
  Object v = doc.getFirstValue(field);
  if(v != null) {
    if(v instanceof IndexableField) {
      return ((IndexableField)v).stringValue();
    }
    return v.toString();
  }
  return null;
}
 
Example 9
Source File: TestRandomFlRTGCloud.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public Collection<String> assertRTGResults(final Collection<FlValidator> validators,
                                           final SolrInputDocument expected,
                                           final SolrDocument actual) {
  final Object value =  actual.getFirstValue(resultKey);
  assertNotNull(getFlParam() + " => no value in actual doc", value);
  assertTrue(USAGE + " must be an String: " + value, value instanceof String);

  // trivial sanity check
  assertFalse(USAGE + " => blank string", value.toString().trim().isEmpty());
  return Collections.<String>singleton(resultKey);
}
 
Example 10
Source File: TestRandomFlRTGCloud.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public Collection<String> assertRTGResults(final Collection<FlValidator> validators,
                                           final SolrInputDocument expected,
                                           final SolrDocument actual) {
  final Object actualVal =  actual.getFirstValue(resultKey);
  assertNotNull(getFlParam() + " => no value in actual doc", actualVal);
  assertEquals(getFlParam(), expectedVal, actualVal);
  return Collections.<String>singleton(resultKey);
}
 
Example 11
Source File: TestPutSolrRecord.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that given SolrServer contains the expected SolrDocuments.
 */
private static void verifySolrDocuments(SolrClient solrServer, Collection<SolrDocument> expectedDocuments)
        throws IOException, SolrServerException {

    solrServer.commit();

    SolrQuery query = new SolrQuery("*:*");
    QueryResponse qResponse = solrServer.query(query);
    Assert.assertEquals(expectedDocuments.size(), qResponse.getResults().getNumFound());

    // verify documents have expected fields and values
    for (SolrDocument expectedDoc : expectedDocuments) {
        boolean found = false;
        for (SolrDocument solrDocument : qResponse.getResults()) {
            boolean foundAllFields = true;
            for (String expectedField : expectedDoc.getFieldNames()) {
                Object expectedVal = expectedDoc.getFirstValue(expectedField);
                Object actualVal = solrDocument.getFirstValue(expectedField);
                foundAllFields = expectedVal.equals(actualVal);
            }

            if (foundAllFields) {
                found = true;
                break;
            }
        }
        Assert.assertTrue("Could not find " + expectedDoc, found);
    }
}
 
Example 12
Source File: TestPutSolrContentStream.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that given SolrServer contains the expected SolrDocuments.
 */
private static void verifySolrDocuments(SolrClient solrServer, Collection<SolrDocument> expectedDocuments)
        throws IOException, SolrServerException {

    solrServer.commit();

    SolrQuery query = new SolrQuery("*:*");
    QueryResponse qResponse = solrServer.query(query);
    Assert.assertEquals(expectedDocuments.size(), qResponse.getResults().getNumFound());

    // verify documents have expected fields and values
    for (SolrDocument expectedDoc : expectedDocuments) {
        boolean found = false;
        for (SolrDocument solrDocument : qResponse.getResults()) {
            boolean foundAllFields = true;
            for (String expectedField : expectedDoc.getFieldNames()) {
                Object expectedVal = expectedDoc.getFirstValue(expectedField);
                Object actualVal = solrDocument.getFirstValue(expectedField);
                foundAllFields = expectedVal.equals(actualVal);
            }

            if (foundAllFields) {
                found = true;
                break;
            }
        }
        Assert.assertTrue("Could not find " + expectedDoc, found);
    }
}
 
Example 13
Source File: TestCloudNestedDocsSort.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Test 
public void test() throws SolrServerException, IOException {
  final boolean asc = random().nextBoolean();
  final String dir = asc ? "asc": "desc";
  final String parentFilter = "+parentFilter_s:("+matchingParent+" "+anyValsSpaceDelim(2)+")^=0";
  String childFilter = "+childFilter_s:("+matchingChild+" "+anyValsSpaceDelim(4)+")^=0";
  final String fl = "id,type_s,parent_id_s1,val_s1,score,parentFilter_s,childFilter_s,parentTie_s1";
  String sortClause = "val_s1 "+dir+", "+"parent_id_s1 "+ascDesc();
  if(rarely()) {
    sortClause ="parentTie_s1 "+ascDesc()+","+sortClause;
  }
  final SolrQuery q = new SolrQuery("q", "+type_s:child^=0 "+parentFilter+" "+
        childFilter ,
      "sort", sortClause, 
      "rows", ""+maxDocs,
      "fl",fl);

  final QueryResponse children = client.query(q);
  
  final SolrQuery bjq = random().nextBoolean() ? 
       new SolrQuery(// top level bjq
         "q", "{!parent which=type_s:parent}(+type_s:child^=0 "+parentFilter+" "+ childFilter+")",
         "sort", sortClause.replace("val_s1", "childfield(val_s1)"),
         "rows", ""+maxDocs, "fl", fl)
       :
      new SolrQuery(// same bjq as a subordinate clause
         "q", "+type_s:parent "+parentFilter+" +{!v=$parentcaluse}",
         "parentcaluse","{!parent which=type_s:parent v='"+(childFilter).replace("+", "")+"'}",
         "sort", sortClause.replace("val_s1", "childfield(val_s1,$parentcaluse)"),
         "rows", ""+maxDocs, "fl", fl);

  final QueryResponse parents = client.query(bjq);
  
  Set<String> parentIds = new LinkedHashSet<>();
  assertTrue("it can never be empty for sure", parents.getResults().size()>0);
  for(Iterator<SolrDocument> parentIter = parents.getResults().iterator(); parentIter.hasNext();) {
    for (SolrDocument child : children.getResults()) {
      assertEquals("child", child.getFirstValue("type_s"));
      final String parentId = (String) child.getFirstValue("parent_id_s1");
      if( parentIds.add(parentId) ) { // in children the next parent appears, it should be next at parents 
        final SolrDocument parent = parentIter.next();
        assertEquals("parent", parent.getFirstValue("type_s"));
        final String actParentId = ""+ parent.get("id");
        if (!actParentId.equals(parentId)) {
          final String chDump = children.toString().replace("SolrDocument","\nSolrDocument");
          System.out.println("\n\n"+chDump+"\n\n");
          System.out.println("\n\n"+parents.toString().replace("SolrDocument","\nSolrDocument")
              +"\n\n");
        }
        assertEquals(""+child+"\n"+parent,actParentId, parentId);
      }
    }
  }

  
}