从 web api 2 和 return 一个文档中查询 ravendb

query ravendb from web api 2 and return one document

我想使用 Asp.net Web API 2 和 RavenDB 执行以下操作。

  1. 向 RavenDB 发送一个字符串。
  2. 查找包含名为 UniqueString 的字段的文档,该字段包含我传递给 RavenDB 的字符串。
  3. Return 匹配的文档,或 "YES/NO a document with that string exists" - 消息。

我对 NoSQL 和 RavenDB 是全新的,所以这被证明是相当困难的:-)我希望有人能帮助我,我认为这实际上很容易做到,尽管我无法做到找到任何显示它的指南。

这与 WebAPI 2 无关,但您可以结合使用 RavenDb 和 WebAPI 2 来完成您的要求。

首先您需要在文档上有一个索引(或者让 RavenDb 自动为您创建一个)并且 property/properties 您希望被索引。这个索引可以用这样的代码创建:

public class MyDocument_ByUniqueString : AbstractIndexCreationTask<MyDocument>
{
    public override string IndexName
    {
        get { return "MyDocumentIndex/ByUniqueString"; }
    }

    public MyDocument_ByUniqueString()
    {
        Map = documents => from doc in documents
                            select new
                            {
                                doc.UniqueString
                            };
    }
}

或在 RavenDb Studio 中创建:

from doc in docs.MyDocuments
select new {
    doc.UniqueString
}

之后,您可以对该索引执行 "advanced document query"(在您的情况下来自 WebAPI 2 控制器或类似控制器)并传入 Lucene 通配符:

using (var session = documentStore.OpenSession())
{
    var result = session.Advanced
        .DocumentQuery<MyDocument>("MyDocumentIndex/ByUniqueString")
        .Where("UniqueString: *uniq*")
        .ToList();
}

此查询将 return 所有 属性 "UniqueString" 包含术语 "uniq" 的文档。我的文档如下所示:

{
    "UniqueString": "This is my unique string"
}

但是请注意,Lucene 中的这类通配符可能性能不佳,因为它们可能需要扫描大量文本。在 RavenDB 文档中甚至有一个警告:

Warning

RavenDB allows to search by using such queries but you have to be aware that leading wildcards drastically slow down searches. Consider if you really need to find substrings, most cases looking for words is enough. There are also other alternatives for searching without expensive wildcard matches, e.g. indexing a reversed version of text field or creating a custom analyzer.

http://ravendb.net/docs/article-page/2.0/csharp/client-api/querying/static-indexes/searching

希望对您有所帮助!

  1. 让 WebApi 端点工作以收集您的输入。这与 RavenDB 无关。
  2. 使用 RavenDB 客户端,使用 Linq 或其他方法之一查询数据库。
  3. 检索文档后,您可能需要为 return 预期结果编写一些逻辑。

我跳过了用要查询的数据填充数据库的步骤。我会在您的应用程序中尽可能多地利用 RavenDB 客户端工具,而不是尝试使用 HTTP api.