上一节中我们演示了在SolrAdmin中使用Facet功能来进行分组统计,这一节我们看看怎样使用.NET开发Solr中的Facet功能。在讲Facet功能的同时,
我们看下.Net中怎样使用Solr查询。使用的客户端工具是easysorl.net,大家可以去codeplex下载。这个工具很好用。
看如下图,下图就是我们要演示的功能
1.模糊查询
模糊查询就是搜索指定的汉字得到一个结果。下面的示例就是查询商品名称中包含白色的所有商品,最终得到的结果如下图
代码
- public void Query()
- {
-
- if (string.IsNullOrWhiteSpace(textBox1.Text.Trim()))
- {
- #region 查询全部
-
- var result = operations.Query("collection1", "/select", SolrQuery.All, null);
- var header = binaryResponseHeaderParser.Parse(result);
- var examples = binaryQueryResultsParser.Parse(result);
- this.dataGridView1.DataSource = examples.ToList();
-
- #endregion
- }
- else
- {
- #region 按商品名模糊查询
-
- ISolrQuery solrQuery = new SolrQuery(textBox1.Text.Trim());
- var result = operations.Query("collection1", "/select", solrQuery, null);
- var header = binaryResponseHeaderParser.Parse(result);
- var examples = binaryQueryResultsParser.Parse(result);
- this.dataGridView1.DataSource = examples.ToList();
-
- #endregion
-
- }
- }
2.精确查询
在查询的时候,有时候我们要根据商品的ID或者商品的编码精确的查询到某一个商品。下面的例子就演示了按商品编码精确查询的功能。
- if (string.IsNullOrWhiteSpace(textBox2.Text.Trim()))
- {
- return;
- }
- string conditon = "ProductCode:" + textBox2.Text.Trim();
- ISolrQuery solrQuery = new SolrQuery(conditon);
- var result = operations.Query("collection1", "/select", solrQuery, null);
- var header = binaryResponseHeaderParser.Parse(result);
- var examples = binaryQueryResultsParser.Parse(result);
- this.dataGridView1.DataSource = examples.ToList();
3.Facet分组统计
在查询的时候,有的时候,我们需要对查询的结果进行分组,比如想知道包含这个商品的每个分类有多少商品,每个价格区间有多少商品。
下面的例子统计每个分类有多少商品。
-
-
-
-
-
- private void button3_Click(object sender, EventArgs e)
- {
- label3.Visible = true;
-
- var dic=new Dictionary<string,ICollection<string>>();
- dic["facet"] = new string[] { "true" };
-
- var options = new List<string>();
- options.Add("CategoryName");
- dic["facet.field"] = options;
- var result = operations.Query("collection1", "/select", SolrQuery.All,dic);
- var header = binaryResponseHeaderParser.Parse(result);
- var examples = binaryQueryResultsParser.Parse(result);
-
-
- IDictionary<string, IList<FacetField>> facetDic=new BinaryFacetFieldsParser().Parse(result);
- string strFacet = "";
- foreach (var item in facetDic)
- {
- strFacet +="分组字段:"+item.Key+"\r\n";
- foreach (var facetItem in item.Value)
- {
- strFacet += facetItem.Name + "(" + facetItem.Count.ToString() + ")" + "---";
- }
- }
- label3.Text = strFacet;
- this.dataGridView1.DataSource = examples.ToList();
- }
Demo下载: http://download.csdn.net/detail/zx13525079024/7385945