如何解决有效比较存储在数据库中的长文本字符串
我将应用程序事件存储在一个数据库中,该事件是从其他文本文件中提取的。
事件对象如下:
public class LogEvent
{
public DateTime DateTime { get; set; }
public LogLevel Level { get; set; }
public string Message { get; set; } //can be lengthy
}
请注意,我不拥有此结构,也无法将任何属性(如唯一的Guid)添加到原始生成的对象中(但是我可以扩展该类,并根据已有的信息创建其他数据库列)。
我的问题是我想确保我不会两次插入相同的事件,尽管可以将其复制到不同的文件中。 DateTime + Level 属性不足以实现相等性:可能在同一时间发生不同的事件。
因此,每当我向数据库中插入一个事件/事件列表时,我都需要与消息属性进行比较,由于潜在的字符串长度,该属性非常低效:这意味着我需要传输一种或另一种方式来插入已插入事件的 Message 属性,以将其与数据库索引进行本地比较。
我考虑过要创建一个附加属性 Hashcode ,该属性将存储 Message 属性的String.GetHashCode()。但是,我读过here,这不是一个好习惯,因为Hashcode的实现在程序执行之间不稳定(可能会发生冲突,但是这种风险可以接受)
因此,我遇到了以下问题:如何从长字符串中建立比较值,该字符串可以确定性,快速计算/比较并具有可接受的冲突率? 。字符串最多可以包含数千个字符。
我知道乔恩·斯基特(Jon Skeet)对类似问题here的回答,但是它已经相当古老(将近10年),我想知道2020年是否有更好的方法!
感谢您的提示!
解决方法
展开我的评论:使用Murmur3
非加密哈希算法。您可以从NuGet此处获取:https://www.nuget.org/packages/murmurhash/
- 请勿使用内置的
GetHashCode()
,因为如您所料,在过程之外继续存在是不安全的。 - 您可以(但您不应该)使用加密安全的哈希函数,因为它们的计算量很大,而且运算速度通常较慢(不一定是故意变慢的,但如果使用SHA-256,微不足道的计算,然后我将成为找到用于比特币采矿的SHA-256哈希的亿万富翁)。
- 而像Murmur这样的哈希函数被设计为具有快速且公平防冲突的功能。
这就是我要做的:
- 编写一个函数,将您的
LogEntry
序列化为可重用的MemoryStream
以便通过MurmurHash进行哈希处理(我链接到的NuGet程序包无法自动对任何对象进行哈希处理,即使它确实,则需要严格定义的哈希操作-实际上,在内存中序列化是目前的“最佳”方法。只要您重新使用MemoryStream
,这不会很昂贵。 - 将哈希存储在数据库中和/或在内存中缓存以减少IO操作。
在您的情况下:
interface ILogEventHasher
{
Int32 Compute32BitMurmurHash( LogEvent logEvent );
}
// Register this class as a singleton service in your DI container.
sealed class LogEventHasher : IDisposable
{
private readonly MemoryStream ms = new MemoryStream();
public Int32 Compute32BitMurmurHash( LogEvent logEvent )
{
if( logEvent is null ) throw new ArgumentNullException( nameof(logEvent) );
this.ms.Position = 0;
this.ms.Length = 0; // This resets the length pointer,it doesn't deallocate memory.
using( BinaryWriter wtr = new BinaryWriter( this.ms,Encoding.UTF8 ) )
{
wtr.Write( logEvent.DateTime );
wtr.Write( logEvent.Level );
wtr.Write( logEvent.Message );
}
this.ms.Position = 0; // This does NOT reset the Length pointer.
using( Murmur32 mh = MurmurHash.Create32() )
{
Byte[] hash = mh.ComputeHash( this.ms );
return BitConverter.ToInt32( hash ); // `hash` will be 4 bytes long.
}
// Reset stream state:
this.ms.Position = 0;
this.ms.Length = 0;
// Shrink the MemoryStream if it's grown too large:
const Int32 TWO_MEGABYTES = 2 * 1024 * 1024;
if( this.ms.Capacity > TWO_MEGABYTES )
{
this.ms.Capacity = TWO_MEGABYTES;
}
}
public void Dispose()
{
this.ms.Dispose();
}
}
要过滤内存中的LogEvent
实例,只需使用HashSet<( DateTime utc,Int32 hash )>
。
我不建议使用HashSet<Int32>
(仅存储Murmur哈希码),因为使用32位非密码安全的哈希码不能给我足够的信心,让我相信哈希码冲突不会发生-但是将其与DateTime
值结合起来可以给我足够的信心(DateTime
值消耗64位或8个字节-因此每个 memoized {{1 }}将需要12个字节。给定.NET的2GiB数组/对象大小限制(并假设HashSet加载因子为0.75),意味着您最多可以在内存中存储 134,217,728 个缓存的哈希码。希望足够了!
这是一个例子:
LogEvent
如果要直接在数据库中执行此操作,请为运行以下形式的interface ILogEventFilterService
{
Boolean AlreadyLoggedEvent( LogEvent e );
}
// Register as a singleton service.
class HashSetLogEventFilter : ILogEventFilterService
{
// Somewhat amusingly,internally this HashSet will use GetHashCode() - rather than our own hashes,because it's storing a kind of user-level "weak-reference" to a LogEvent in the form of a ValueTuple.
private readonly HashSet<( DateTime utc,Int32 hash )> hashes = new HashSet<( DateTime utc,Int32 hash )>();
private readonly ILogEventHasher hasher;
public HashSetLogEventFilter( ILogEventHasher hasher )
{
this.hasher = hasher ?? throw new ArgumentNullException( nameof(hasher) );
}
public Boolean AlreadyLoggedEvent( LogEvent e )
{
if( e is null ) throw new ArgumentNullException( nameof(e) );
if( e.DateTime.Kind != DateTimeKind.Utc )
{
throw new ArgumentException( message: "DateTime value must be in UTC.",paramName: nameof(e) );
}
Int32 murmurHash = this.hasher.HashLogEvent( e );
var t = ( utc: e.DateTime,hash: murmurHash );
return this.hashes.Add( t ) == false;
}
}
语句的存储过程的表值参数定义自定义用户定义表类型:
MERGE
CREATE TABLE dbo.LogEvents (
Utc datetime2(7) NOT NULL,MurmurHash int NOT NULL,LogLevel int NOT NULL,Message nvarchar(4000) NOT NULL
);
,
步骤1.按长度比较它们。它会切断大多数。 步骤2.比较第一个字符长度相同的字符串...等等。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。