Index a dynamic object using NEST

后端 未结 1 925
忘了有多久
忘了有多久 2020-12-14 12:11

I am building an API application that essentially allows a user to build a document, which can be structured however they want, that will be stored in Elasticsearch. Essenti

相关标签:
1条回答
  • 2020-12-14 12:50

    There's a couple ways to do this.

    Trying to index the document as type dynamic won't work, but you can index it as an object through the IndexRequest object.

    dynamic dynamicDoc = new { /*fill in document format here*/ };
    ElasticClient esClient = new ElasticClient(esSettings);
    
    IndexRequest<object> request = new IndexRequest<object>(dynamicDoc)
    {
        Index = "someindex",
        Type = "SomeType",
        Id = "someid"
    };
    
    esClient.Index<object>(request);
    

    Or if dealing with documents in bulk

    List<dynamic> Documents = new List<dynamic>();
    //Populate Documents
    
    BulkDescriptor descriptor = new BulkDescriptor();
    foreach(var doc in Documents)
    {
        descriptor.Index<object>(i => i
            .Index("someindex")
            .Type("SomeType")
            .Id("someid")
            .Document(doc));
    }
    
    esClient.Bulk(descriptor);
    

    NEST (or more accurately, Elasticsearch.Net) also has a .Raw method variant attached to the ElasticClient class, which can index raw JSON. Using Raw.Index() let's us do things like this:

    string documentJson = JsonConvert.SerializeObject(document.Document);
    
    ElasticsearchResponse<string> result = esClient.Raw.Index(document.Index, document.Type, document.Id, documentJson);
    

    The type descriptor for the response is the type you'll expect the response to be in (string means you'll have a serialized json response which you can deserialize and do something with). This allows us to sidestep the entire object type issue and NEST indexes the document into Elasticsearch exactly as expected.

    0 讨论(0)
提交回复
热议问题