V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
china521
V2EX  ›  分享创造

一个奇技淫巧的 tags 推荐算法.

  •  
  •   china521 · 2018-11-23 10:22:55 +08:00 · 2807 次点击
    这是一个创建于 1952 天前的主题,其中的信息可能已经有所发展或是发生改变。

    想实现一个 tags 关联度算法, 大多是基于 Go/PHP 这些的, 没找到 SQL 实现的, 朋友推荐了一个算法

    https://github.com/Iwark/jaccard

    感觉这样不 GEEK,要是直接能写到 SQL 语句里就很 666 了,研究了半天,SQL 本身的逻辑实现这个蹩脚

    于事,根据算法宗旨,写出来了下面这行语句,按关联度倒序, 看懂的拿走不谢~~

    10 跟 7 是两个 tag 的 ID,有多个就多个 repalce 套一下

    select id, m from 
    (
    select id, group_concat('|', article_tags.tag_id,'|') as m from article
    right join article_tags on article_tags.article_id=article.id
    group by article.id
    ) as tt 
    order by length(replace(replace(tt.m, '|10|', space(100)), '|7|', space(100))) 
    desc
    

    有更好的实现方法,欢迎分享~

    第 1 条附言  ·  2018-11-23 13:00:57 +08:00
    ```
    select id, m from
    (
    select id, group_concat('|', article_tags.tag_id,'|') as m from article
    right join article_tags on article_tags.article_id=article.id
    group by article.id
    ) as tt
    order by length(replace(replace(tt.m, '|10|', space(100)), '|7|', space(100))) - length(tt.m)*2
    desc
    ```

    这样就是变相的加上关联权重了.
    5 条回复    2018-11-23 20:51:54 +08:00
    CRVV
        1
    CRVV  
       2018-11-23 12:05:47 +08:00   ❤️ 1
    1. 原来那个 repo 里的算法毫无新意,就是自己建了一个 Hash Table 来计数
    2. 楼主的 SQL 写得很怪异,建议认真学一下 SQL
    3. 楼主的 SQL 写错了,原来的算法是 1|2|3-1|2 的相关性大于 1|2|3|4-1|2,这条 SQL 的结果应该是反的
    china521
        2
    china521  
    OP
       2018-11-23 12:47:24 +08:00
    ```
    select id, m from
    (
    select id, group_concat('|', article_tags.tag_id,'|') as m from article
    right join article_tags on article_tags.article_id=article.id
    group by article.id
    ) as tt
    order by length(replace(replace(tt.m, '|10|', space(100)), '|7|', space(100))) - length(tt.m)*10
    desc
    ```

    确实是
    按原始长度权重减一下就对了,SQL 怪异没办法,group_concat 的真不能在 order 里计算, 必须用子语句
    china521
        3
    china521  
    OP
       2018-11-23 12:51:37 +08:00
    哈哈,好像不能这样〜〜〜 233,当我没发
    china521
        4
    china521  
    OP
       2018-11-23 12:58:34 +08:00
    这样加上权重有点暴力
    leoleoasd
        5
    leoleoasd  
       2018-11-23 20:51:54 +08:00
    运算交给程序做
    sql 只做 sql 该做的事情
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   962 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 21:53 · PVG 05:53 · LAX 14:53 · JFK 17:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.