有效比较存储在数据库中的长文本字符串

如何解决有效比较存储在数据库中的长文本字符串

我将应用程序事件存储在一个数据库中,该事件是从其他文本文件中提取的。

事件对象如下:

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这样的哈希函数被设计为具有快速且公平防冲突的功能。

这就是我要做的:

  1. 编写一个函数,将您的LogEntry序列化为可重用的MemoryStream以便通过MurmurHash进行哈希处理(我链接到的NuGet程序包无法自动对任何对象进行哈希处理,即使它确实,则需要严格定义的哈希操作-实际上,在内存中序列化是目前的“最佳”方法。只要您重新使用MemoryStream,这不会很昂贵。
  2. 将哈希存储在数据库中和/或在内存中缓存以减少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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-