3

我能够按相似度对三元组搜索进行排序,并按相似度得分进行过滤,这意味着必须有一些与每条记录相关的客观排名。我怎样才能获得那个分数?

我正在使用的代码:

q = "search query"  # ie "honey"

A = 1.0
B = 0.4
C = 0.2
D = 0.1

total_weight = A + B + C + D

trigram = A/total_weight * TrigramSimilarity('name', q) + \
    B/total_weight * TrigramSimilarity('brand__name', q) + \
    B/total_weight * TrigramSimilarity('description', q) + \
    D/total_weight * TrigramSimilarity('category__name', q)

results = Product.objects.annotate(
        similarity=trigram
    ).filter(similarity__gt=0.1).order_by('-similarity')

如果我能够过滤similarity__gt=0.1或排序-similarity,是否还可以查看(并希望附加)每条记录的相似度排名?

4

1 回答 1

0

我想到了。比预期的要容易得多。原始 SQL 引导我朝着正确的方向前进。上面的代码创建了以下语句:

SELECT "listings_product"."id",
       "listings_product"."name",
       "listings_product"."slug",
       "listings_product"."brand_id",
       "listings_product"."category_id",
       "listings_product"."description",
       "listings_product"."featured",
       "listings_product"."image",
       "listings_product"."created_date",
       "listings_product"."created_by_id",
       "listings_product"."last_updated",
       ((((0.5882352941176471 * SIMILARITY("listings_product"."name", "honey")) + (0.23529411764705885 * SIMILARITY("listings_brand"."name", "honey"))) + (0.23529411764705885 * SIMILARITY("listings_product"."description", "honey"))) + (0.05882352941176471 * SIMILARITY("listings_category"."name", "honey"))) 
           AS "similarity" 
FROM "listings_product" 
    INNER JOIN "listings_brand" ON ("listings_product"."brand_id" = "listings_brand"."id") 
    LEFT OUTER JOIN "listings_category" ON ("listings_product"."category_id" = "listings_category"."id") 
WHERE ((((0.5882352941176471 * SIMILARITY("listings_product"."name", "honey")) + (0.23529411764705885 * SIMILARITY("listings_brand"."name", "honey"))) + (0.23529411764705885 * SIMILARITY("listings_product"."description", "honey"))) + (0.05882352941176471 * SIMILARITY("listings_category"."name", "honey"))) > 0.01 
ORDER BY "similarity" DESC;

AS "similarity"向我展示了分数可能已经被返回。我回到我的 django shell,运行查询,然后尝试:

results[0].similarity

哪个返回0.225113122340511

于 2019-09-03T02:30:28.460 回答