gpt4 book ai didi

c# - C#Nest,Elastic Search:更新并添加到列表中的字段

转载 作者:行者123 更新时间:2023-12-02 23:00:12 24 4
gpt4 key购买 nike

这可能是一个愚蠢的问题,但我是 flex 搜索和嵌套的新手。

我有一个类

Person
{
public string Id {get; set;}
public string Name {get; set;}
public IList<string> PhoneNumbers {get; set;}
}

我想做的就是通过添加电话号码来更新它。

现在我正在用2个查询来做,但是我想知道是否有一种方法可以用1个来管理它。
        // See if the Person already exists
var result = NestClient.Search<Person>(s => s
.Index(_indexName)
.Take(1)
.Query(q => q
.Term(p => p.Name, person.Name)
&& q.Term(p => p.Id, person.Id)));

if (result.ServerError != null)
{
throw result.OriginalException;

}
if (result.Documents.FirstOrDefault() == null)
{
var response = NestClient.Index<Person>(person);
if (response.ServerError != null)
{
throw response.OriginalException;
}
}
else
{
// If it does exist update and overwrite
var savedPerson = result.Documents.First();

IList<string> oldNums = SavedPerson.PhoneNumbers;
IList<string> newNums = newPerson.PhoneNumbers;
var combinedNums = oldNums.Concat(newNums);

newPerson.PhoneNumbers = combinedNums.ToList<string>();

var response = NestClient.Update(DocumentPath<Person>
.Id(newPerson.Id),
u => u.Doc(newPerson).DocAsUpsert(true));
if (response.ServerError != null)
{
throw response.OriginalException;
}
}

基本上,我希望我的upsert添加到电话号码的现有列表(如果存在)。

最佳答案

如果可以选择脚本,则可以使用scripted update来完成。

在数组中更新后具有重复项的选项

var updateResponse = client.Update<Document, DocumentPartial>(DocumentPath<Document>.Id(1), descriptor => descriptor
.Script(@"ctx._source.array += tab;")
.Params(p => p.Add("tab", new[] {4, 5, 3})));

没有
var updateResponse = client.Update<Document, DocumentPartial>(DocumentPath<Document>.Id(1), descriptor => descriptor
.Script(@"ctx._source.array += tab; ctx._source.array.unique();")
.Params(p => p.Add("tab", new[] {4, 5, 3})));

完整示例:
public class DocumentPartial
{
public int[] Array { get; set; }
}

public class Document
{
public int Id { get; set; }

public int[] Array { get; set; }
}

var client = new ElasticClient(settings);

client.CreateIndex(indexName, descriptor => descriptor
.Mappings(map => map
.Map<Document>(m => m.AutoMap())));

var items = new List<Document>
{
new Document
{
Id = 1,
Array = new[] {1,2,3}
}
};

var bulkResponse = client.IndexMany(items);

client.Refresh(indexName);

var updateResponse = client.Update<Document, DocumentPartial>(DocumentPath<Document>.Id(1), descriptor => descriptor
.Script(@"ctx._source.array += tab; ctx._source.array.unique();")
.Params(p => p.Add("tab", new[] {4, 5, 3})));

希望能帮助到你。

关于c# - C#Nest,Elastic Search:更新并添加到列表中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36073938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com