分享

Solr学习(六)利用Solr的C#客户端SolrNet检索数据

xioaxu790 2014-12-7 20:47:43 发表于 连载型 [显示全部楼层] 回帖奖励 阅读模式 关闭右栏 0 16984
本帖最后由 xioaxu790 于 2014-12-7 20:57 编辑
问题导读
1、你如何学习Solr?
2、如何利用Solr的C#客户端库SolrNet访问Solr?



本文接上一篇:Solr学习(五)DIH增量、定时导入并检索数据
利用Solr的C#客户端库SolrNet访问Solr:
参考: https://github.com/mausch/SolrNe ... tion/Basic-usage.md
First, we have to map the Solr document to a class. Let's use a subset of the default schema that comes with the Solr distribution:
  1. public class Product {
  2.     [SolrUniqueKey("id")]
  3.     public string Id { get; set; }
  4.     [SolrField("manu_exact")]
  5.     public string Manufacturer { get; set; }
  6.     [SolrField("cat")]
  7.     public ICollection<string> Categories { get; set; }
  8.     [SolrField("price")]
  9.     public decimal Price { get; set; }
  10.     [SolrField("inStock")]
  11.     public bool InStock { get; set; }
  12. }
复制代码



It's just a POCO with some attributes: SolrField maps the attribute to a Solr field and SolrUniqueKey (optional but recommended) maps an attribute to a Solr unique key field.

Now we'll write some tests using this mapped class. Let's initialize the library:
  1. [TestFixtureSetUp]
  2. public void FixtureSetup() {
  3.     Startup.Init<Product>("http://localhost:8983/solr");
  4. }
复制代码

Let's add a document (make sure you have a running Solr instance before running this test):
  1. [Test]
  2. public void Add() {
  3.     var p = new Product {
  4.         Id = "SP2514N",
  5.         Manufacturer = "Samsung Electronics Co. Ltd.",
  6.         Categories = new[] {
  7.             "electronics",
  8.             "hard drive",
  9.         },
  10.         Price = 92,
  11.         InStock = true,
  12.     };
  13.     var solr = ServiceLocator.Current.GetInstance<ISolrOperations<Product>>();
  14.     solr.Add(p);
  15.     solr.Commit();
  16. }
复制代码

Let's see if the document is where we left it:
  1. [Test]
  2. public void Query() {
  3.     var solr = ServiceLocator.Current.GetInstance<ISolrOperations<Product>>();
  4.     var results = solr.Query(new SolrQueryByField("id", "SP2514N"));
  5.     Assert.AreEqual(1, results.Count);
  6.     Console.WriteLine(results[0].Price);
  7. }
复制代码

好了,基本的东西差不多就这样了,接下来目标是用asp.net做一个真正的全文检索的页面。

没找到任何评论,期待你打破沉寂

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条