Django Postgres Trigram 搜索 - 如何查看每个结果的分数?

Django Postgres Trigram search - how can I see the score of each result?

我能够按相似度对三元组搜索进行排序并按相似度分数进行过滤,这意味着必须有一些 objective 等级与每条记录相关联。我如何访问该分数?

我使用的代码:

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 排序,是否还可以查看(并希望附加)每条记录的相似度排名?

我明白了。比预期的容易得多。原始 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