Solr検索ベース
32136 ワード
この例では、クラスライブラリとコードの両方を使用します.
http://www.cnblogs.com/TerryLiang/archive/2011/04/17/2018962.html
C#を使用して、検索、インデックス作成、削除、更新プロセスをシミュレートします.Demoのスクリーンショットは次のとおりです.
一、準備作業:
まず、エンティティークラスProductを準備します.
public class Product
{
public string ID { get; set; }
public string Name { get; set; }
public String[] Features { get; set; }
public float Price { get; set; }
public int Popularity { get; set; }
public bool InStock { get; set; }
public DateTime Incubationdate_dt { get; set; }
}
このエンティティークラスの逆シーケンス化クラスProductDeserializerを作成します.
class ProductDeserializer : IObjectDeserializer<Product>
{
public IEnumerable<Product> Deserialize(SolrDocumentList result)
{
foreach (SolrDocument doc in result)
{
yield return new Product()
{
ID = doc["id"].ToString(),
Name = doc["name"].ToString(),
Features = (string[])((ArrayList)doc["features"]).ToArray(typeof(string)),
Price = (float)doc["price"],
Popularity = (int)doc["popularity"],
InStock = (bool)doc["inStock"],
Incubationdate_dt = (DateTime)doc["incubationdate_dt"]
};
}
}
}
プロジェクトにEasyNetを導入する.Solr.dll.
二、検索の作成:
Solrクライアントの初期化操作を実行します.
#region
static List<SolrInputDocument> docs = new List<SolrInputDocument>();
static OptimizeOptions optimizeOptions = new OptimizeOptions();
static ISolrResponseParser<NamedList, ResponseHeader> binaryResponseHeaderParser = new BinaryResponseHeaderParser();
static IUpdateParametersConvert<NamedList> updateParametersConvert = new BinaryUpdateParametersConvert();
static ISolrUpdateConnection<NamedList, NamedList> solrUpdateConnection = new SolrUpdateConnection<NamedList, NamedList>() { ServerUrl = "http://localhost:8080/solr/" };
static ISolrUpdateOperations<NamedList> updateOperations = new SolrUpdateOperations<NamedList, NamedList>(solrUpdateConnection, updateParametersConvert) { ResponseWriter = "javabin" };
static ISolrQueryConnection<NamedList> connection = new SolrQueryConnection<NamedList>() { ServerUrl = "http://localhost:8080/solr/" };
static ISolrQueryOperations<NamedList> operations = new SolrQueryOperations<NamedList>(connection) { ResponseWriter = "javabin" };
static IObjectDeserializer<Product> exampleDeserializer = new ProductDeserializer();
static ISolrResponseParser<NamedList, QueryResults<Product>> binaryQueryResultsParser = new BinaryQueryResultsParser<Product>(exampleDeserializer);
#endregion
まず、例としていくつかのデータを内蔵したデータソースをシミュレートします.
List<Product> products = new List<Product>();
Product juzi = new Product
{
ID = "SOLR1000",
Name = " ",
Features = new String[] {
" ",
" , ",
" "},
Price = 2.0f,
Popularity = 100,
InStock = true,
Incubationdate_dt = new DateTime(2006, 1, 17, 0, 0, 0, DateTimeKind.Utc)
};
products.Add(juzi);
var doc = new SolrInputDocument();
doc.Add("id", new SolrInputField("id", juzi.ID));
doc.Add("name", new SolrInputField("name", juzi.Name));
doc.Add("features", new SolrInputField("features", juzi.Features));
doc.Add("price", new SolrInputField("price", juzi.Price));
doc.Add("popularity", new SolrInputField("popularity", juzi.Popularity));
doc.Add("inStock", new SolrInputField("inStock", juzi.InStock));
doc.Add("incubationdate_dt", new SolrInputField("incubationdate_dt", juzi.Incubationdate_dt));
docs.Add(doc);
Product pingguo = new Product
{
ID = "SOLR1002",
Name = " ",
Features = new String[] {
" ",
" ",
" "
},
Price = 1.7f,
Popularity = 50,
InStock = true,
Incubationdate_dt = new DateTime(2010, 1, 17, 0, 0, 0, DateTimeKind.Utc)
};
products.Add(pingguo);
var doc2 = new SolrInputDocument();
doc2.Add("id", new SolrInputField("id", pingguo.ID));
doc2.Add("name", new SolrInputField("name", pingguo.Name));
doc2.Add("features", new SolrInputField("features", pingguo.Features));
doc2.Add("price", new SolrInputField("price", pingguo.Price));
doc2.Add("popularity", new SolrInputField("popularity", pingguo.Popularity));
doc2.Add("inStock", new SolrInputField("inStock", pingguo.InStock));
doc2.Add("incubationdate_dt", new SolrInputField("incubationdate_dt", pingguo.Incubationdate_dt));
docs.Add(doc2);
dataGridView1.DataSource = products;
これらのデータは同時にList
1.索引の作成:
インデックスの作成とは、元のデータをSolrに渡し、次の図のようにSolrディレクトリの下に指定したフォーマットファイルを作成することです.
インデックスの作成は、実際にはUpdateを使用してcollection 1にデータPOSTを渡します.コードは次のとおりです.
var result = updateOperations.Update("collection1", "/update", new UpdateOptions() { OptimizeOptions = optimizeOptions, Docs = docs });
var header = binaryResponseHeaderParser.Parse(result);
lbl_info.Text= string.Format("Update Status:{0} QTime:{1}", header.Status, header.QTime);
インデックスが成功すると、Solr管理インタフェースでクエリーを実行できます.
注:マネージャを使用して検索するたびに、右上隅に検索に使用するURLが表示されます.
http://localhost:8080/solr/collection1/select?q=*%3A*&wt=json&indent=true
これらのパラメータの意味は、いくつかのドキュメントをクエリーして情報を取得するのが簡単です.
2.クエリーの作成
クエリーは、サーバにリクエストを送信し、サーバが結果を返すのを待つプロセスです.任意の言語でリクエストを開始し、結果を受け入れることができる限り、クライアントを使用します.
まずISolrQueryオブジェクトを作成し、検索キーワードを入力します.キーワードの構築方法はSolr管理インタフェースから推論できます.
nameに「アップル」という情報を検索するには、管理インタフェースに入力する必要があります.
Solrがクエリーを構築する方法を知りたい場合は、DebugQueryオプションをチェックしてデバッグ情報を取得します.
名前という列でのみ検索するという意味です.
コードには次のように書く必要があります.
ISolrQuery query = new SolrQuery("name:"+keyWord);
安全問題は自分で考える.
しかし、すべてをクエリーするのは簡単です.
ISolrQuery query = SolrQuery.All;
クエリー条件をサーバーに送信した後、サーバーから返されたデータをオブジェクト表示に復元すると、クエリー操作が完了します.具体的な操作コードは以下の通りです.
ISolrQuery query = SolrQuery.All;
if (!string.IsNullOrWhiteSpace(keyWord))
{
query = new SolrQuery("name:"+keyWord);
}
var result = operations.Query("collection1", "/select", query, null);
var header = binaryResponseHeaderParser.Parse(result);
var examples = binaryQueryResultsParser.Parse(result);
lbl_info.Text= string.Format("Query Status:{0} QTime:{1} Total:{2}", header.Status, header.QTime, examples.NumFound);
dataGridView1.DataSource = examples.ToList();
3.インクリメンタル索引
実際には、データが追加されたり変更されたりすることが多いので、インデックスをタイムリーに更新して新しいデータをクエリーしやすくする必要があります.インクリメンタルインデックスが必要です.これは、初回インデックスと同様に、既存のデータを更新したい場合は、新しいデータをもう一度コミットすればいいです.異なるデータのコミットを増やしたい場合は.データ判定基準はidで、これは構成項目で、中D:apache-tomcat-7.0でよい.57\webapps\solr\solr_home\collection1\conf\schema.xml検索:
プライマリ・キーとして理解できます.
コードは次のとおりです.
var docs = new List<SolrInputDocument>();
Product hetao = new Product
{
ID = "SOLR1003",
Name = " ",
Features = new String[] {
" ",
" ",
" "
},
Price = 1.7f,
Popularity = 50,
InStock = true,
Incubationdate_dt = new DateTime(2010, 1, 17, 0, 0, 0, DateTimeKind.Utc)
};
var doc2 = new SolrInputDocument();
doc2.Add("id", new SolrInputField("id", hetao.ID));
doc2.Add("name", new SolrInputField("name", hetao.Name));
doc2.Add("features", new SolrInputField("features", hetao.Features));
doc2.Add("price", new SolrInputField("price", hetao.Price));
doc2.Add("popularity", new SolrInputField("popularity", hetao.Popularity));
doc2.Add("inStock", new SolrInputField("inStock", hetao.InStock));
doc2.Add("incubationdate_dt", new SolrInputField("incubationdate_dt", hetao.Incubationdate_dt));
docs.Clear();
docs.Add(doc2);
var result = updateOperations.Update("collection1", "/update", new UpdateOptions() { OptimizeOptions = optimizeOptions, Docs = docs });
var header = binaryResponseHeaderParser.Parse(result);
lbl_info.Text= string.Format("Update Status:{0} QTime:{1}", header.Status, header.QTime);
4.索引の削除
データベース削除と同様に、もちろんプライマリ・キーに従って削除します.転送削除Optionは、プライマリ・キー名とプライマリ・キー値を同時にサーバに持ち込んで送信すればよい.
具体的な操作コードは以下の通りです.
var result = updateOperations.Update("collection1", "/update", new UpdateOptions() { OptimizeOptions = optimizeOptions, DelById = new string[] { id } });
var header = binaryResponseHeaderParser.Parse(result);
lbl_info.Text=string.Format("Update Status:{0} QTime:{1}", header.Status, header.QTime);
これにより、インデックスの作成、インデックスの削除、クエリーの更新が最も基本的なプロセスが完了しました.この例のクエリーの速度は、管理インタフェースを直接操作するほど速くありません.なぜなら、シーケンス化と逆シーケンス化が行われているためです.上記のように、どの言語でもリクエストと受信応答を開始できればクエリーができ、このプロセスを回避し、クエリーの効率を高めることができます.
コードのダウンロード