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

利用Solr的C#客户端库SolrNet访问Solr:

参考: https://github.com/mausch/SolrNet/blob/master/Documentation/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:

public class Product {
    [SolrUniqueKey("id")]
    public string Id { get; set; }

    [SolrField("manu_exact")]
    public string Manufacturer { get; set; }

    [SolrField("cat")]
    public ICollection<string> Categories { get; set; }

    [SolrField("price")]
    public decimal Price { get; set; }

    [SolrField("inStock")]
    public bool InStock { get; set; }
}

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:

[TestFixtureSetUp]
public void FixtureSetup() {
    Startup.Init<Product>("http://localhost:8983/solr");
}

Let's add a document (make sure you have a running Solr instance before running this test):

[Test]
public void Add() {
    var p = new Product {
        Id = "SP2514N",
        Manufacturer = "Samsung Electronics Co. Ltd.",
        Categories = new[] {
            "electronics",
            "hard drive",
        },
        Price = 92,
        InStock = true,
    };

    var solr = ServiceLocator.Current.GetInstance<ISolrOperations<Product>>();
    solr.Add(p);
    solr.Commit();
}

Let's see if the document is where we left it:

[Test]
public void Query() {
    var solr = ServiceLocator.Current.GetInstance<ISolrOperations<Product>>();
    var results = solr.Query(new SolrQueryByField("id", "SP2514N"));
    Assert.AreEqual(1, results.Count);
    Console.WriteLine(results[0].Price);
}


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

未完待续。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值