当我们在scala中使用Solrj时,查询文档中可能不存在的字段值的好方法是什么?让Option[Any]
作为回应是理想的。如果它是一个多值字段,获取空列表将是理想的。
现在我得到NullPointerException:
import org.apache.solr.client.solrj.SolrQuery
import org.apache.solr.client.solrj.impl.CloudSolrClient
import org.apache.solr.client.solrj.request.QueryRequest
import org.apache.solr.common.SolrDocument
import scala.collection.JavaConversions._
val solrClientBuilder = new CloudSolrClient.Builder
val client: CloudSolrClient = solrClientBuilder.withZkHost("zookeeper.myhost.net:2181").build()
client.setDefaultCollection("skus")
client.setIdField("sku")
val solrQuery = new SolrQuery()
solrQuery.setQuery(s"sku:13614994")
solrQuery.setFields("inventoryLevel, skuCCs") // skuCCs might not be present in document
val params = new QueryRequest(solrQuery).getParams
val solrDocumentList: List[SolrDocument] = for {
doc <- client.query(solrAlias, params).getResults.toList
} yield doc.asInstanceOf[SolrDocument]
val inventoryLevel: String = solrDocumentList.map(
_.getFieldValue("inventoryLevel").toString
).headOption.getOrElse("unknown")
// this throws NullPointerException if there is no such field in document:
val skuCCs: List[String] = for {
doc <- solrDocumentList
skuCC <- doc.getFieldValues("skuCCs").toList
} yield skuCC.toString
Solr是版本6.6。
答案 0 :(得分:0)
找到它。
val skuCCs: List[String] = for {
doc <- solrDocumentList
name <- doc.getFieldNames
if name == "skuCCs"
skuCC <- doc.getFieldValues(name).toList
} yield skuCC.toString