ElasticSearch嵌套插入/更新

问题描述 投票:7回答:1

我使用以下查询创建了弹性索引:

PUT public_site
{
  "mappings": {
    "page": {
      "properties": {
        "url": {
          "type": "string"
        },
        "title":{
          "type": "string"
        },
        "body":{
          "type": "string"
        },
        "meta_description":{
          "type": "string"
        },
        "keywords":{
          "type": "string"
        },
        "category":{
          "type": "string"
        },
        "last_updated_date":{
          "type": "date"
        },
        "source_id":{
        "type":"string"
        }
      }
    }
  }
}

我想使用.net NEST库将文档插入到此索引中。我的问题是.net更新方法的签名对我没有任何意义。

client.Update<TDocument>(IUpdateRequest<TDocument,TPartialDocument>)

Java库对我来说更有意义:

UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index("index");
updateRequest.type("type");
updateRequest.id("1");
updateRequest.doc(jsonBuilder()
        .startObject()
            .field("gender", "male")
        .endObject());
client.update(updateRequest).get();

在NEST,TDocumentTPartialDocument课程来自哪里?这些C#类是否代表我的索引?

elasticsearch nest
1个回答
21
投票

TDocumentTPartialDocument是POCO类型的通用类型参数

  • 代表Elasticsearch(TDocument)和
  • 执行部分更新时,Elasticsearch(TPartialDocument)中文档的一部分的表示。

在完全更新的情况下,TDocumentTPartialDocument可以指代相同的具体POCO类型。我们来看一些示例来演示。

让我们使用您在上面定义的映射创建索引。首先,我们可以使用POCO类型表示文档

public class Page
{
    public string Url { get; set; }

    public string Title { get; set; }

    public string Body { get; set; }

    [String(Name="meta_description")]
    public string MetaDescription { get; set; }

    public IList<string> Keywords { get; set; }

    public string Category { get; set; }

    [Date(Name="last_updated_date")]
    public DateTimeOffset LastUpdatedDate { get; set; }

    [String(Name="source_id")]
    public string SourceId { get; set; }
}

默认情况下,当NEST序列化POCO属性时,它使用camel大小写命名约定。因为你的索引有某些属性的蛇形外壳,例如"last_updated_date",我们可以使用属性覆盖NEST序列化它们的名称。

接下来,让我们创建要使用的客户端

var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var pagesIndex = "pages";
var connectionSettings = new ConnectionSettings(pool)
        .DefaultIndex(pagesIndex)
        .PrettyJson()
        .DisableDirectStreaming()
        .OnRequestCompleted(response =>
            {
                // log out the request
                if (response.RequestBodyInBytes != null)
                {
                    Console.WriteLine(
                        $"{response.HttpMethod} {response.Uri} \n" +
                        $"{Encoding.UTF8.GetString(response.RequestBodyInBytes)}");
                }
                else
                {
                    Console.WriteLine($"{response.HttpMethod} {response.Uri}");
                }

                Console.WriteLine();

                // log out the response
                if (response.ResponseBodyInBytes != null)
                {
                    Console.WriteLine($"Status: {response.HttpStatusCode}\n" +
                             $"{Encoding.UTF8.GetString(response.ResponseBodyInBytes)}\n" +
                             $"{new string('-', 30)}\n");
                }
                else
                {
                    Console.WriteLine($"Status: {response.HttpStatusCode}\n" +
                             $"{new string('-', 30)}\n");
                }
            });

var client = new ElasticClient(connectionSettings);

连接设置的配置方式在开发过程中很有用;

  1. DefaultIndex() - 默认索引已配置为"pages"。如果没有在请求上传递显式索引名称,并且不能为POCO推断索引名称,则将使用默认索引。
  2. PrettyJson() - Pretetify(即缩进)json请求和响应。这对于查看Elasticsearch发送和接收的内容非常有用。
  3. DisableDirectStreaming() - 默认情况下,NEST将POCO序列化为请求流,并从响应流中反序列化响应类型。禁用此直接流将缓冲内存流中的请求和响应字节,允许我们在OnRequestCompleted()中记录它们
  4. OnRequestCompleted() - 在收到回复后调用。这使我们能够在开发过程中注销请求和响应。

2,3和4在开发过程中非常有用,但会带来一些性能开销,因此您可能决定不在生产中使用它们。

现在,让我们使用Page mapping创建索引

// delete the index if it exists. Useful for demo purposes so that
// we can re-run this example.
if (client.IndexExists(pagesIndex).Exists)
    client.DeleteIndex(pagesIndex);

// create the index, adding the mapping for the Page type to the index
// at the same time. Automap() will infer the mapping from the POCO
var createIndexResponse = client.CreateIndex(pagesIndex, c => c
    .Mappings(m => m
        .Map<Page>(p => p
            .AutoMap()
        )
    )
);

Take a look at the automapping documentation for more details around how you can control mapping for POCO types

索引新的页面类型非常简单

// create a sample Page
var page = new Page
{
    Title = "Sample Page",
    Body = "Sample Body",
    Category = "sample",
    Keywords = new List<string>
    {
        "sample",
        "example", 
        "demo"
    },
    LastUpdatedDate = DateTime.UtcNow,
    MetaDescription = "Sample meta description",
    SourceId = "1",
    Url = "/pages/sample-page"
};

// index the sample Page into Elasticsearch.
// NEST will infer the document type (_type) from the POCO type,
// by default it will camel case the POCO type name
var indexResponse = client.Index(page);

索引文档将创建文档(如果文档不存在),或覆盖现有文档(如果存在)。 Elasticsearch has optimistic concurrency control可以用来控制它在不同条件下的表现。

我们可以使用Update方法更新文档,但首先是一些背景知识。

我们可以通过指定索引,类型和id从Elasticsearch获取文档。 NEST使这一点变得更容易,因为我们可以从POCO中推断所有这些。当我们创建映射时,我们没有在POCO上指定Id属性;如果NEST看到一个名为Id的属性,它会将其用作文档的id,但因为我们没有,所以这不是问题,因为Elasticsearch会为文档生成id并将其放入文档元数据中。因为文档元数据与源文档是分开的,所以这可以使POCO类型的建模文档有点棘手(但并非不可能);对于给定的响应,我们将通过元数据访问文档的id,并通过_source字段访问源。我们可以在应用程序中将id与我们的源相结合。

解决这个问题的一种更简单的方法是在POCO上有一个id。我们可以在POCO上指定一个Id属性,这将用作文档的id,但如果我们不想要,我们不必调用属性Id,如果我们不想,我们需要告诉NEST哪个属性代表id。这可以使用属性来完成。假设SourceIdPage实例的唯一id,请使用ElasticsearchTypeAttribute IdProperty属性来指定它。也许我们不应该分析这个字符串但是逐字索引,我们也可以通过属性上的属性的Index属性来控制它

[ElasticsearchType(IdProperty = nameof(SourceId))]
public class Page
{
    public string Url { get; set; }

    public string Title { get; set; }

    public string Body { get; set; }

    [String(Name="meta_description")]
    public string MetaDescription { get; set; }

    public IList<string> Keywords { get; set; }

    public string Category { get; set; }

    [Date(Name="last_updated_date")]
    public DateTimeOffset LastUpdatedDate { get; set; }

    [String(Name="source_id", Index=FieldIndexOption.NotAnalyzed)]
    public string SourceId { get; set; }
}

有了这些,我们需要像以前一样重新创建索引,以便这些更改反映在映射中,并且NEST可以在索引Page实例时使用此配置。

现在,回到更新:)我们可以从Elasticsearch获取文档,在应用程序中更新它,然后重新索引它

var getResponse = client.Get<Page>("1");

var page = getResponse.Source;

// update the last updated date 
page.LastUpdatedDate = DateTime.UtcNow;

var updateResponse = client.Update<Page>(page, u => u.Doc(page));

第一个参数是我们想要获取的文档的id,它可以由NEST从Page实例中推断出来。由于我们将整个文档传回这里,我们可以使用.Index()而不是Update(),因为我们正在更新所有字段

var indexResponse = client.Index(page);

但是,由于我们只想更新LastUpdatedDate,不得不从Elasticsearch获取文档,在应用程序中更新它,然后将文档发送回Elasticsearch是很多工作。我们只能使用部分文档将更新的LastUpdatedDate发送到Elasticsearch。 C#匿名类型在这里非常有用

// model our partial document with an anonymous type. 
// Note that we need to use the snake casing name
// (NEST will still camel case the property names but this
//  doesn't help us here)
var lastUpdatedDate = new
{
    last_updated_date = DateTime.UtcNow
};

// do the partial update. 
// Page is TDocument, object is TPartialDocument
var partialUpdateResponse = client.Update<Page, object>("1", u => u
    .Doc(lastUpdatedDate)
);

如果我们需要使用RetryOnConflict(int),我们可以在这里使用乐观并发控制

var partialUpdateResponse = client.Update<Page, object>("1", u => u
    .Doc(lastUpdatedDate)
    .RetryOnConflict(1)
);

通过部分更新,Elasticsearch将获取文档,应用部分更新,然后索引更新的文档;如果文档在获取和更新之间发生变化,Elasticsearch将再次根据RetryOnConflict(1)重试此操作。

希望有帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.