Solr的Scala客户端(scalikesolr)介绍

本文是scalikesolr的wiki的翻译 

后边的代码片段使用了如下文档产生的索引"example/exampledocs/books.json". 

{ 
  "id" : "978-0641723445", 
  "cat" : ["book","hardcover"], 
  "title" : "The Lightning Thief", 
  "author" : "Rick Riordan", 
  "series_t" : "Percy Jackson and the Olympians", 
  "sequence_i" : 1, 
  "genre_s" : "fantasy", 
  "inStock" : true, 
  "price" : 12.50, 
  "pages_i" : 384 
}, 
{ 
  "id" : "978-1423103349", 
  "cat" : ["book","paperback"], 
  "title" : "The Sea of Monsters", 
  "author" : "Rick Riordan", 
  "series_t" : "Percy Jackson and the Olympians", 
  "sequence_i" : 2, 
  "genre_s" : "fantasy", 
  "inStock" : true, 
  "price" : 6.49, 
  "pages_i" : 304 
} 

查询 

简单查询 

使用核心查询参数普通查询参数 

Java代码 
  1. import com.github.seratch.scalikesolr._  
  2.   
  3. val client = Solr.httpServer(new URL("http://localhost:8983/solr")).newClient  
  4. val request = new QueryRequest(writerType = WriterType.JavaBinary, query = Query("author:Rick")) // faster when using WriterType.JavaBinary  
  5. val response = client.doQuery(request)  
  6. println(response.responseHeader)  
  7. println(response.response)  
  8. response.response.documents foreach {  
  9.   case doc => {  
  10.     println(doc.get("id").toString()) // "978-1423103349"  
  11.     println(doc.get("cat").toListOrElse(Nil).toString) // List(book, hardcover)  
  12.     println(doc.get("title").toString()) // "The Sea of Monsters"  
  13.     println(doc.get("pages_i").toIntOrElse(0).toString) // 304  
  14.     println(doc.get("price").toDoubleOrElse(0.0).toString) // 6.49  
  15.   }  
  16. }  



从SolrDocument绑定到对象 

需要无参构造器和字段设置器。也可以指定有一个字符串作为参数的构造器的用户定义类型 

Java代码 
  1. case class PageI(val value: String = "")  
  2. case class Book(  
  3.   var id: String = "",  
  4.   var cat: List[String] = Nil,  
  5.   var price: Double = 0.0,  
  6.   var pageI: PageI = PageI(),  
  7.   var sequenceI: Int = 0 ) {  
  8.   def this() = {  
  9.     this ("", Nil, 0.0, PageI(), 0)  
  10.   }  
  11. }  
  12. val book = doc.bind(classOf[Book])  
  13. println(book.id) // "978-1423103349"  
  14. println(book.cat.size) // 2  
  15. println(book.price) // 6.49  
  16. println(book.pageI.value) // 304  
  17. println(book.sequenceI) // 2  



使用高亮 

使用高亮参数: 

Java代码 
  1. val request = new QueryRequest(  
  2.   writerType = WriterType.JSON, // but JSON format might be slow...  
  3.   query = Query("author:Rick"),  
  4.   sort = Sort("page_i desc")  
  5. )  
  6. request.highlighting = HighlightingParams(true)  
  7. val response = client.doQuery(request)  
  8. println(response.highlightings)  
  9. response.highlightings.keys foreach {  
  10.   case key => {  
  11.     println(key + " -> " + response.highlightings.get(key).get("author").toString)  
  12.     // "978-0641723445" -> "[i]Rick[/i] Riordan"  
  13.   }  
  14. }  



使用MoreLikeThis 

使用推荐: 

Java代码 
  1. val request = new QueryRequest(Query("author:Rick"))  
  2. request.moreLikeThis = MoreLikeThisParams(  
  3.   enabled = true,  
  4.   count = 3,  
  5.   fieldsToUseForSimilarity = FieldsToUseForSimilarity("body")  
  6. )  
  7. val response = client.doQuery(request)  
  8. println(response.moreLikeThis)  
  9. response.response.documents foreach {  
  10.   doc => {  
  11.     val id = doc.get("id").toString  
  12.     response.moreLikeThis.getList(id) foreach {  
  13.       case recommendation => {  
  14.         println(recommendation) // "SolrDocument(WriterType(standard),,Map(start -> 0, numFound -> 0))"  
  15.       }  
  16.     }  
  17.   }  
  18. }  



使用多层面查询(FacetQuery) 

使用简单的多层面查询参数: 

Java代码 
  1. val request = new QueryRequest(Query("author:Rick"))  
  2. request.facet = new FacetParams(  
  3.   enabled = true,  
  4.   params = List(new FacetParam(Param("facet.field"), Value("title")))  
  5. )  
  6. val response = client.doQuery(request)  
  7. println(response.facet.facetFields)  
  8. response.facet.facetFields.keys foreach {  
  9.   case key => {  
  10.     val facets = response.facet.facetFields.getOrElse(key, new SolrDocument())  
  11.     facets.keys foreach {  
  12.       case facetKey => println(facetKey + " -> " + facets.get(facetKey).toIntOrElse(0))  
  13.       // "thief" -> 1, "sea" -> 1, "monster" -> 1, "lightn" -> 1  
  14.     }  
  15.   }  
  16. }  



使用结果集分组(Groupiong) /字段折叠(Field Collapsing) 

Java代码 
  1. val request = new QueryRequest(Query("genre_s:fantasy"))  
  2. request.group = new GroupParams(  
  3.   enabled = true,  
  4.   field = Field("author_t")  
  5. )  
  6. val response = client.doQuery(request)  
  7. println(response.groups.toString)  
  8. response.groups.groups foreach {  
  9.   case group => println(group.groupValue + " -> " + group.documents.toString)  
  10.   // "r.r" -> List(SolrDocument(...  
  11.   // "glen" -> List(SolrDocument(...  
  12. }  



分布式查询 

使用分布式查询: 

Java代码 
  1. val request = new QueryRequest(Query("genre_s:fantasy"))  
  2. request.shards = new DistributedSearchParams(  
  3.   shards = List(  
  4.     "localhost:8984/solr",  
  5.     "localhost:8985/solr"  
  6.   )  
  7. )  
  8. val response = client.doQuery(request)  
  9. println(response.groups.toString)  



数据导入命令(DIH Command) 

数据导入的命令: 

Java代码 
  1. val request = new DIHCommandRequest(command = "delta-import")  
  2. val response = client.doDIHCommand(request)  
  3. println(response.initArgs)  
  4. println(response.command)  
  5. println(response.status)  
  6. println(response.importResponse)  
  7. println(response.statusMessages)  




文档更新 

更新Solr索引的XML信息: 

添加/更新文档 

向Solr中添加文档: 

Java代码 
  1. val request = new UpdateRequest()  
  2. val doc1 = SolrDocument(  
  3.   writerType = WriterType.JSON,  
  4.   rawBody = """  
  5.   { "id" : "978-0641723445",  
  6.     "cat" : ["book","hardcover"],  
  7.     "title" : "The Lightning Thief",  
  8.     "author" : "Rick Riordan",  
  9.     "series_t" : "Percy Jackson and the Olympians",  
  10.     "sequence_i" : 1,  
  11.     "genre_s" : "fantasy",  
  12.     "inStock" : true,  
  13.     "price" : 12.50,  
  14.     "pages_i" : 384  
  15.   }"""  
  16. )  
  17. val doc2 = SolrDocument(  
  18. writerType = WriterType.JSON,  
  19. rawBody = """  
  20.   { "id" : "978-1423103349",  
  21.     "cat" : ["book","paperback"],  
  22.     "title" : "The Sea of Monsters",  
  23.     "author" : "Rick Riordan",  
  24.     "series_t" : "Percy Jackson and the Olympians",  
  25.     "sequence_i" : 2,  
  26.     "genre_s" : "fantasy",  
  27.     "inStock" : true,  
  28.     "price" : 6.49,  
  29.     "pages_i" : 304  
  30.   }"""  
  31. )  
  32. request.documents = List(doc1, doc2)  
  33. val response = client.doUpdateDocuments(request)  
  34. client.doCommit(new UpdateRequest)  



删除文档 

Java代码 
  1. val request = new DeleteRequest(uniqueKeysToDelete = List("978-0641723445"))  
  2. val response = client.doDeleteDocuments(request)  
  3. client.doCommit(new UpdateRequest)  
  4. Commit  
  5.   
  6. val response = client.doCommit(new UpdateRequest())  
  7. Rollback  
  8.   
  9. val response = client.doRollback(new UpdateRequest())  
  10. Optimize  
  11.   
  12. val response = client.doOptimize(new UpdateRequest())  
  13. Add / Update documents in CSV format  
  14.   
  15. val request = new UpdateRequest(  
  16.   requestBody = "id,name,sequence_i\n0553573403,A Game of Thrones,1\n..."  
  17. )  
  18. val response = client.doUpdateDocumentsInCSV(request)  
  19. client.doCommit(new UpdateRequest)  



以XML格式更新: 

Java代码 
  1. val request = new UpdateRequest(  
  2.   requestBody = "<optimize/>"  
  3. )  
  4. val response = client.doUpdateInXML(request)  



以JSON格式更新: 

Java代码 
  1. val request = new UpdateRequest(  
  2.   writerType = WriterType.JSON,  
  3.   requestBody = "{ 7b1debea0390ffbb4e49e2f145a1625ea6ec7011quot;optimize7b1debea0390ffbb4e49e2f145a1625ea6ec7011quot;: { 7b1debea0390ffbb4e49e2f145a1625ea6ec7011quot;waitFlush7b1debea0390ffbb4e49e2f145a1625ea6ec7011quot;:false, 7b1debea0390ffbb4e49e2f145a1625ea6ec7011quot;waitSearcher7b1debea0390ffbb4e49e2f145a1625ea6ec7011quot;:false } }"  
  4. )  
  5. val response = client.doUpdateInJSON(request)  



从更新格式中加载文档 

不支持JSON格式 

XML格式 

Java代码 
  1. val xmlString = "<add><doc><field name=ece0aa4e60e0be0d48ee70d07ac10cec4e21eecaquot;employeeIdece0aa4e60e0be0d48ee70d07ac10cec4e21eecaquot;>05991</field><field name=ece0aa4e60e0be0d48ee70d07ac10cec4e21eecaquot;officeece0aa4e60e0be0d48ee70d07ac10cec4e21eecaquot;>Bridgewater</field>..."  
  2. val docs = UpdateFormatLoader.fromXMLString(xmlString)  
  3. docs foreach {  
  4.   case doc => {  
  5.     println("employeeId:" + doc.get("employeeId").toString()) // "05991"  
  6.     println("office:" + doc.get("office").toString()) // "Bridgewater"  
  7.   }  
  8. }  



CSV格式 

Java代码 
  1. val csvString = "id,name,sequence_i\n0553573403,A Game of Thrones,1\n..."  
  2. val docs = UpdateFormatLoader.fromCSVString(csvString)  
  3. docs foreach {  
  4.   case doc => {  
  5.     println(doc.get("id")) // "0553573403"  
  6.     println(doc.get("name")) // "A Game of Thrones"  
  7.     println(doc.get("sequence_i").toIntOrElse(0)) // 1  
  8.   }  
  9. }  




Ping 

Java代码 
    1. val response = client.doPing(new PingRequest())  
    2. println(response.status) // "OK"  
posted @ 2013-01-21 23:04  纶巾客  阅读(1900)  评论(2编辑  收藏  举报