我正在使用 Xamarin 6.1 开发适用于 iOS 和 Android 的应用,并且我正在使用 Xamarin.Forms 2.3.1 该应用程序使用包含 Guid Id 的 ZXing.Net.Mobile.Forms 2.1.4 扫描 QR,并将其作为字符串保存到我的 ElasticSearch 中。为了连接 ElasticSearch,我使用的是 NEST 2.x
问题是,当我再次扫描同一个 QR(当我确定它已经被索引时)它被检测为一个新的,即使值是相同的(都作为字符串进行比较)。但是,在存储或比较它们之前,我尝试从 id 中删除破折号 (-) 并且它有效。
这是我的模型:
public class Box
{
[String(Analyzer = "null")]
public string id { get; set; }
public string lastUpdate { get; set; }
}
result.Text 是我从二维码中得到的,我确定它是一个字符串,这就是我索引它的方式:
scannedQR = result.Text;
// INDEXING
var timeStamp = GetTimestamp(DateTime.Now);
var customBox = new Box {
id= scannedQR,
lastUpdate = timeStamp
};
var res = client.Index(customBox, p => p
.Index("airstorage")
.Type("boxes")
.Id(scannedQR)
.Refresh()
);
这就是我检查二维码是否已经存在的方法:
var resSearch = client.Search<Box>(s => s
.Index("airstorage")
.Type("boxes")
.From(0)
.Size(10)
.Query(q => q
.Term(p => p.id, scannedQR)
)
);
if (resSearch.Documents.Count() > 0) {
Console.WriteLine("EXISTING");
}
else {
Console.WriteLine("NEW BOX");
}
我还尝试在创建 ElasticSearch 中的索引时将属性设置为 .NotAnalyse,如 here 中的建议但还是不行。
有人知道吗?欢迎一切!
谢谢!
最佳答案
我会将您的Box
POCO 上的id
字段设置为不分析
public class Box
{
[String(Index = FieldIndexOption.NotAnalyzed)]
public string id { get; set; }
public string lastUpdate { get; set; }
}
id
属性仍将被索引,但不会进行分析,因此将被逐字索引。
我还会使用
检查文档是否存在var existsResponse = client.DocumentExists<Box>("document-id", e => e.Index("airstorage").Type("boxes"));
if (!existsResponse.Exists)
{
Console.WriteLine("document exists")
}
但是,实际上我认为你想要的是 use optimistic concurrency control对于索引调用中的创建文档,即如果文档不存在则对其进行索引,但如果它确实存在则返回 409 冲突无效响应。 OpType.Create
可用于此
var indexResponse = client.Index(box, i => i
.OpType(OpType.Create)
.Index("airstorage")
.Type("boxes"));
if (!indexResponse.IsValid)
{
if (indexResponse.ApiCall.HttpStatusCode == 409)
{
Console.WriteLine("document exists");
}
else
{
Console.WriteLine($"error indexing document: {indexResponse.DebugInformation}");
}
}
关于elasticsearch - 使用 Xamarin.Forms 与 NEST 的 Guid ID 比较不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39488207/