我正在尝试从教育问题记录列表中筛选出一些常见的标签组合。
在这个例子中,我只考虑了两个标签的例子(标签-标签),我应该得到一个结果示例: "point" + "curve"(65条记录) "add" + "subtract"(40条记录) ...
以下是所需的SQL语句结果:
逻辑本身是没有问题的,但是由于我对这个平台相当陌生,所以不确定是否有更短的解决方法可以使其更加高效。目前,查询需要大约45秒的时间来比较大约5K X 5K的标签 :(
附加:标签类。
在这个例子中,我只考虑了两个标签的例子(标签-标签),我应该得到一个结果示例: "point" + "curve"(65条记录) "add" + "subtract"(40条记录) ...
以下是所需的SQL语句结果:
SELECT a.tag, b.tag, count(*)
FROM examquestions.dbmanagement_tag as a
INNER JOIN examquestions.dbmanagement_tag as b on a.question_id_id = b.question_id_id
where a.tag != b.tag
group by a.tag, b.tag
基本上,我们需要将不同的标签与相同的问题识别成一个列表,并将它们分组到相同的匹配标签组合中。
我尝试使用Django queryset做类似的查询:
twotaglist = [] #final set of results
alphatags = tag.objects.all().values('tag', 'type').annotate().order_by('tag')
betatags = tag.objects.all().values('tag', 'type').annotate().order_by('tag')
startindex = 0 #startindex reduced by 1 to shorten betatag range each time the atag changes. this is to reduce the double count of comparison of similar matches of tags
for atag in alphatags:
for btag in betatags[startindex:]:
if (atag['tag'] != btag['tag']):
commonQns = [] #to check how many common qns
atagQns = tag.objects.filter(tag=atag['tag'], question_id__in=qnlist).values('question_id').annotate()
btagQns = tag.objects.filter(tag=btag['tag'], question_id__in=qnlist).values('question_id').annotate()
for atagQ in atagQns:
for btagQ in btagQns:
if (atagQ['question_id'] == btagQ['question_id']):
commonQns.append(atagQ['question_id'])
if (len(commonQns) > 0):
twotaglist.append({'atag': atag['tag'],
'btag': btag['tag'],
'count': len(commonQns)})
startindex=startindex+1
逻辑本身是没有问题的,但是由于我对这个平台相当陌生,所以不确定是否有更短的解决方法可以使其更加高效。目前,查询需要大约45秒的时间来比较大约5K X 5K的标签 :(
附加:标签类。
class tag(models.Model):
id = models.IntegerField('id',primary_key=True,null=False)
question_id = models.ForeignKey(question,null=False)
tag = models.TextField('tag',null=True)
type = models.CharField('type',max_length=1)
def __str__(self):
return str(self.tag)
t.tag = a_tag
这将始终为True
。 - Burhan Khalid