cogear
V2EX  ›  数据库

请问怎么利用数据库索引实现域名匹配查询?数据库存了域名列表,现在要查询一个给定域名是否命中列表

  •  
  •   cogear · Apr 12, 2025 · 2460 views
    This topic created in 398 days ago, the information mentioned may be changed or developed.

    举例

    我使用的是 Microsoft SQL Server, 假设不考虑通配符,数据库Hostname列建了索引,并存了一些域名:

    假设现在有这么个域名 www.sub.test.com, 我应该查询数据库获得 test.comsub.test.com

    我的实现

    查询Hostname列时,like '%test.com',这样的写法是无法命中索引的,只有%放在末尾才能命中文本列的索引。

    所以我存储了另一列 ReversedHostname ,把域名反转存储。SQL 查询时把要查询的域名也反转,然后 Where 语句这么写

    WHERE Reverse(要查询的域名) like ReversedHostname + '.%'
    

    但是实践证明这也不能命中索引。

    只有这样的查询

    Where ReversedHostname like 'moc.tset.%'
    

    才能命中索引。

    有没有更好的实现?大家做域名匹配一般使用什么方式

    12 replies    2025-04-14 12:38:51 +08:00
    beck123
        1
    beck123  
       Apr 12, 2025
    laminux29
        2
    laminux29  
       Apr 12, 2025
    直接 es 不香嘛? es 专为高性能搜索而生,它的次时代索引,对这些传统关系型数据库来说,简直是降维打击。
    cogear
        3
    cogear  
    OP
       Apr 12, 2025
    @a1010795186 我去,好思路!
    opengps
        4
    opengps  
       Apr 12, 2025
    force index
    kingcanfish
        5
    kingcanfish  
       Apr 12, 2025
    你换个思路,com.test.sub.www 这样存 , 写个函数转换下顺序不就可以了
    meiyiliya
        6
    meiyiliya  
       Apr 12, 2025
    test.com = com.test
    sub.test.com = com.test.sub
    hostname like 'com.test%'
    llsquaer
        7
    llsquaer  
       Apr 12, 2025
    有点像梯子软件的域名匹配啊。参考下 clash 的匹配算法不一定要用数据库
    meshell
        8
    meshell  
       Apr 12, 2025
    6 楼正确
    cogear
        9
    cogear  
    OP
       Apr 12, 2025
    @kingcanfish
    @meiyiliya

    要查询的域名是 www.sub.test.com
    数据库 hostname 列存的是 test.com sub.test.com
    AlphaXM
        10
    AlphaXM  
       Apr 13, 2025
    最近在研究 bind-dlz,这是 DNS 服务器 Bind9 的一个扩展模块,支持从数据库查询 dns 记录。附上链接 https://bind-dlz.sourceforge.net/mysql_example.html
    cheng6563
        11
    cheng6563  
       Apr 14, 2025
    WHERE Reverse(要查询的域名)

    你这也没反转过来存啊...
    cogear
        12
    cogear  
    OP
       Apr 14, 2025
    @cheng6563 反转存储的列名是 ReversedHostname 。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   891 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 20:51 · PVG 04:51 · LAX 13:51 · JFK 16:51
    ♥ Do have faith in what you're doing.