使用.net调用Solr

2019-03-27 01:17|来源: 网路

1.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SolrNet;
using SampleSolrApp.Models;
using SolrNet.Schema;
using SolrNet.Attributes;

/// <summary>
///Class2 的摘要说明
/// </summary>
public class Class2
{
 public Class2()
 {
  //
  //TODO: 在此处添加构造函数逻辑
  //

        Product p = new Product();
 }

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

    [SolrField("name")]
    public string Name { get; set; }

    [SolrField("myself")]
    public string MySelf { get; set; }


    [SolrField("yourself")]
    public string YourSelf { get; set; }

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

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

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

    [SolrField("popularity")]
    public int Popularity { get; set; }

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

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

 

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

 

 

//=====================================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SolrNet;
using SampleSolrApp.Models;
using Microsoft.Practices.ServiceLocation;
using SolrNet.Commands.Parameters;

public partial class MyTest : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            ISolrOperations<Class2> solr = ServiceLocator.Current.GetInstance<ISolrOperations<Class2>>();
        }
        catch (NullReferenceException exp)
        {
            Startup.Init<Class2>("http://localhost:8983/solr");
        }

        //delete2();
        //add2();
        query2();

    }

    #region 成功的了

    /// <summary>
    /// 添加数据
    /// </summary>
    public void add2()
    {
        //Class2 p = new Class2
        //{
        //    Id = "SP2221",
        //    Name = "name 2222",
        //    MySelf = "myself 2222",
        //    YourSelf="yourself 2222",
        //    Manufacturer = "manu 2223",
        //    Categories = new[] {
        //        "cat 2224",
        //        "cat 2225",
        //    },
        //    Features = new[]{
        //        "features2226",
        //        "features2227",
        //    },
        //    Popularity = 6,
        //    Price = 92,
        //    InStock = true,
        //};

        //Class2 p = new Class2();
        //p.Id = "china";
        //p.Name = "中华人民共和国";
        //p.MySelf = "王才华";
        //p.YourSelf = "理正软件";
        //p.Manufacturer = "Leading Soft";
        //p.Categories = new[]{
        //    "MIS",
        //    "CAD"
        //};
        //p.Features = new[]{
        //    "Expencive",
        //    "No User"
        //};
        //p.Popularity = 55;
        //p.Price = 11111;
        //p.InStock = false;

        Class2 p = new Class2();
        p.Id = "chinaNo";
        p.Name = "没有这个";
        p.MySelf = "李";

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

    /// <summary>
    /// 查询数据
    /// </summary>
    public void query2()
    {
        ISolrOperations<Class2> solr = ServiceLocator.Current.GetInstance<ISolrOperations<Class2>>();

        //=========================Simple query==========================
        //ISolrQueryResults<Class2> results = solr.Query(new SolrQuery("2222")); //从默认字段中搜索
        //ISolrQueryResults<Class2> results = solr.Query(new SolrQuery("popularity:6")); //从指定的字段中进行搜索
        //ISolrQueryResults<Class2> results = solr.Query(new SolrQuery("中华*")); //模糊查询

        //========================Query by field==========================
        //ISolrQueryResults<Class2> results = solr.Query(new SolrQueryByField("popularity", "6")); //从指定的字段中进行搜索

        //========================Query by range==========================
        //ISolrQueryResults<Class2> results = solr.Query(new SolrQueryByRange<decimal>("price", 10000m, 12222.50m)); //从指定字段的范围区间进行搜索

        //=====================Query by list of values====================
        //ISolrQueryResults<Class2> results = solr.Query(new SolrQueryInList("name", "2222", "中华人民共和国")); //从集合中检索
        //ISolrQueryResults<Class2> results = solr.Query(new SolrQuery("name:2222 OR name:中华人民共和国")); //从集合中检索

        //===================="Any value" query===========================
        //ISolrQueryResults<Class2> results = solr.Query(new SolrHasValueQuery("name")); //包含某个字段的记录

        //====================Query operators=============================
        //ISolrQueryResults<Class2> results = solr.Query(new SolrQuery("2222") && new SolrQuery("myself")); //且的关系,两个条件都需满足  "2222 AND myself"
        //ISolrQueryResults<Class2> results = solr.Query(new SolrQuery("2222") || new SolrQuery("Leading Soft")); //或的关系,两个结果集合并  "2222 Leading Soft"
        //ISolrQueryResults<Class2> results = solr.Query(new SolrQuery("2222") + new SolrQuery("Leading Soft")); //或的关系,两个结果集相加 "2222 Leading Soft"
        //ISolrQueryResults<Class2> results = solr.Query(!new SolrQuery("2222")); // 不包含的结果集 "-2222"
        //ISolrQueryResults<Class2> results = solr.Query(new SolrQuery("2222") - new SolrQuery("my")); //包含2222但不包含my "2222 - my"
        //ISolrQueryResults<Class2> results = solr.Query(new SolrQuery("2222") + !new SolrQuery("my")); //包含2222但不包含my "2222 - my"
        //ISolrQueryResults<Class2> results = solr.Query(new SolrMultipleCriteriaQuery(new[] { new SolrQuery("2222"), new SolrQuery("Leading Soft") })); //与+含义相同
        //ISolrQueryResults<Class2> results = solr.Query(new SolrMultipleCriteriaQuery(new[] { new SolrQuery("2222"), new SolrQuery("myself") }, "AND")); //与&&含义相同

        //====================Filter queries===============================
        //ISolrQueryResults<Class2> results = solr.Query(SolrQuery.All, new QueryOptions {
        //    FilterQueries = new ISolrQuery[] {
        //        new SolrQueryByField("name", "2222"),
        //        new SolrQueryByRange<decimal>("price", 1m, 200m),
        //    }
        //});   //从All结果集里面再进行过滤

        //=======================Fields=====================================
        //ISolrQueryResults<Class2> results = solr.Query(new SolrQuery("2222"), new QueryOptions { Fields = new[] { "id", "manu", "name", "price" } }); //只查询出特定的列

        //=======================Sorting====================================
        //ISolrQueryResults<Class2> results = solr.Query(SolrQuery.All,
        //    new QueryOptions {
        //        OrderBy = new[] {
        //            new SortOrder("name", Order.DESC),
        //            SortOrder.Parse("id asc")
        //        }
        //    });  //排序

        //======================Pagination==================================
        //ISolrQueryResults<Class2> results = solr.Query("2222", new QueryOptions { Start = 10, Rows = 25 });  //从指定位置开始,搜索指定记录信息

        //====================Additional parameters=========================
        //ISolrQueryResults<Class2> results = solr.Query(SolrQuery.All,
        //    new QueryOptions {
        //        ExtraParams = new Dictionary<string, string> {
        //        { "timeAllowed", "100" }
        //        }
        //    });

        ISolrQueryResults<Class2> results = solr.Query(SolrQuery.All,
            new QueryOptions
            {
                ExtraParams = new Dictionary<string, string> {
                { "qt", "standard" }
                }
            });

        //=====================LocalParams================================
        //ISolrQueryResults<Class2> results = solr.Query(new LocalParams { { "type", "dismax" }, { "qf", "myself" } } + new SolrQuery("solr rocks"));

        ////Assert.AreEqual(1, results.Count);
        if (results.Count == 1)
        {
            Response.Write("结果:" + results.Count + "   " + results[0].Price);
        }
        else
        {
            Response.Write("结果:" + results.Count);
        }


        //===============================================================
        //-------------------------Facets--------------------------------
        //===============================================================
        //ISolrQueryResults<Class2> results = solr.Query(SolrQuery.All,
        //    new QueryOptions {
        //        Rows = 0,
        //        Facet = new FacetParameters {
        //            Queries = new[] {
        //                new SolrFacetFieldQuery("category")
        //            }
        //        }
        //    });
        //foreach (var facet in results.FacetFields["category"]) {
        //    Response.Write(facet.Key + ":" + facet.Value + "   ");
        //}
    }

    /// <summary>
    /// 删除数据
    /// </summary>
    public void delete2()
    {
        ISolrOperations<Class2> solr = ServiceLocator.Current.GetInstance<ISolrOperations<Class2>>();
        //solr.Delete("SP2221"); //根据ID进行删除
        solr.Delete(new SolrQuery("*:*")); //删除全部数据
        solr.Commit();
    }

    #endregion
}

 

//=====================================================================================

        String url = "http://localhost:8983/solr/select/?q=solr";
        WebResponse wr_result = null;
        StringBuilder txthtml = new StringBuilder();
        try
        {
            WebRequest wr_req = WebRequest.Create(url);
            wr_result = wr_req.GetResponse();
            Stream ReceiveStream = wr_result.GetResponseStream();
            Encoding encode = System.Text.Encoding.GetEncoding("gb2312");
            StreamReader sr = new StreamReader(ReceiveStream, encode);
            if (true)
            {
                Char[] read = new Char[256];
                int count = sr.Read(read, 0, 256);
                while (count > 0)
                {
                    String str = new String(read, 0, count);
                    txthtml.Append(str);
                    count = sr.Read(read, 0, 256);
                }
            }
        }
        catch (Exception)
        {
            txthtml.Append("err");
        }
        finally
        {
            if (wr_result != null)
            {
                wr_result.Close();
            }
        }

//==============================================================================

            DataTable table = new DataTable();
            string strcon = "Data Source=111;Initial Catalog=MMS_DB;User ID=sa;Password=123;Connect Timeout=30"";
            DbConnection conn = new SqlConnection(strcon);
            conn.Open();
            DbCommand command = new SqlCommand();
            command.Connection = conn;
            command.CommandText = "Select * From AA";
            DbDataAdapter adp = new SqlDataAdapter();
            adp.SelectCommand = command;
            adp.Fill(table);
            conn.Close();


转自:http://blog.csdn.net/tianyitianyi1/article/details/8852254

相关问答

更多
  • 是Solr搜索服务器的一个比较基础的客户端工具,可以非常方便地与Solr搜索服务器进行交互。 最基本的功能就是管理Solr索引,包括添加、更新、删除和查询等。 对于一些比较基础的应用,用Solj基本够用,而且你可以非常容易地通过使用Solrj的API实现与Solr搜索服务器进行交互,实现对Solr的基本管理功能。 如果你的应用比较复杂,可以扩展Solrj来满足需要。
  • 如果你的意思是在.Net而不是Java上运行Solr服务器,那么不,没有端口。 我一直在试图用IKVM 在这里运行它,但它对我来说并不重要,所以我不能在这上面花太多时间。 如果有人能够帮助解决这个问题,那将会很棒。 如果你的意思是从.Net应用程序使用/连接到Solr,那么是的,你可以使用SolrNet或SolrSharp 。 我不久前在这篇博客上发表了博文 。 更新:我使用Solr + IKVM取得了重大进展 。 If you mean running the Solr server on .Net in ...
  • 以下是我在我的项目中使用WS的方法: val itselfNodeFuture = Statix.doParams( Statix.SolrSelectWSReq, List( "wt" -> "json", "q" -> "*:*", "fq" -> "node_type:collection", "fq" -> "id:%d".format( nodeId), "indent" -> "true", "rows ...
  • 我不知道.net的任何Solr端口,您可以查看这个问题以了解更多信息。 我会使用用Java编写的原始Solr,以及用您喜欢的语言编写的客户端库,例如solrnet ,与之通信。 I'm not aware of any Solr port for .net, you can have a look at this question to know more. I would use the original Solr written in Java, and a client library written ...
  • 在cassandra上启用节俭服务器 nodetool enablethrift Enable thrift server on cassandra nodetool enablethrift
  • 这可能是/ etc / hosts的问题。 如果/ etc / hosts不包含主机名的定义,则失败。 尝试将linux-ai1n添加到hosts文件中,例如 127.0.0.1 localhost linux-ai1n This might be a problem with /etc/hosts. If /etc/hosts does not contain the definition of the hostname it fails. Try adding linux-ai1n to the ho ...
  • 我建议你选择已经解决了这个问题的Cloudera CDH 5.2。 / user / share / docs中缺少SOLR文件夹,您必须将solr文件显式放入其中。 I would recommend you to go with Cloudera CDH 5.2 which has already resolved this issue. The SOLR folder is missing in /user/share/docs and you have to explicitly put the s ...
  • 最新的Solr作为独立黑匣子运行。 不要看Tomcat信息的古老教程,它们不再有用。 这是通过.NET客户端连接到它的一个单独问题。 对于客户端部分,SolrNet的源代码版本更新。 它应该与最新的Solr一起工作,主要问题是Solr的URL现在必须包含集合名称,所以http:// localhost:8983 / solr / collectionname 。 检查参数以设置核心或集合或类似。 还有Solr Express,你可能想看看。 Latest Solr runs as standalone bl ...
  • curl -d(或--data)只是发送POST请求到Solr。 如果你想在java中做同样的事情: 使用你喜欢的http库(比如Apache Http Client或其他),并使用它的api将它设置为POST类型的请求并添加所需的数据。 或者你可以使用普通的java,它只是更详细的, 这里是一个例子 curl -d (or --data) is just sending a POST request to Solr. If you want to do the same in java just: use ...
  • 使用浏览器而不是Notepad ++打开solr0.log以确保这是一个真正的问题并找出文件保存的编码 - 如果它不是Unicode,则Solr.NET可能无法搜索它。 已知Notepad ++有中文问题,或者是因为编码(Notepad ++不支持典型的中文编码,如gb或big5),或者是因为默认字体可能支持或不支持中文字符。 浏览器更宽容,并且可以做任何事情来正确显示文件。 事实上,要将非unicode亚洲编码转换为unicode,我经常在浏览器中打开一个文件,它将检测正确的编码并显示原始内容,然后按CT ...