2012-12-21 1 views
0

모델의 쿼리 세트를 반복하고 일치하는 모든 것들을 삭제하기위한 django 코드의 스 니펫이 있습니다. queryset이 ​​커졌으며 이러한 작업은 실제로 주기적 작업으로 설정되므로 속도가 문제가되고 있습니다.큰 쿼리 세트에서 일치하는 모델을 삭제하는 코드를 최적화하는 데 도움이 필요합니다.

누구나 코드를 최적화하려고합니다.

# For the below code, "articles" are just django models 

all_articles = [a reallly large list of articles] 
newest_articles = [some large list of new articles] 
unique_articles = [] 
for new_article in newest_articles: 
    failed = False 
    for old_article in all_articles: 
     # is_similar is just a method which checks if two strings are 
     # identical to a certain degree 
     if is_similar(new_article.blurb, old_article.blurb, 0.9) 
      and is_similar(new_article.title, old_article.title, 0.92): 
      failed = True 
      break 
    if not failed: 
     unique_articles.append(new_article) 
return unique_articles 

감사합니다.

+0

데이터베이스 연산에서'is_similar()'를 정의 할 수 있습니까? –

+0

아무 것도 알지 못한다면 두 입력 문자열이 동일한 지 비교합니다. –

+0

어떤 데이터베이스를 사용하고 있습니까? – atereshkin

답변

1

SQL 수준에서 "퍼지 DISTINCT"를 구현하는 효율적인 방법이없는 것처럼 보이므로 사전 계산 경로를 사용하는 것이 좋습니다. 작은 코드 스 니펫에서 비즈니스 논리를 추측하려고 시도 했으므로이 문제는 근본적으로 다를 수 있지만 오래된 누수가있는 경우 (is_similar 함수로 정의 된대로) 모든 새 문서를 알아야하는 것처럼 들립니다. 이 경우 실행 가능한 접근 방식은 기사 모델에 is_duplicate 필드를 추가하고 기사가 저장 될 때마다 백그라운드 작업에서이를 다시 계산하는 것일 수 있습니다. 예 : (Celery 사용) : 그런 다음 원래의 루틴이 단지

Article.objects.filter(is_duplicate=False, ...recency condition) 
+0

대답 주셔서 감사합니다,이 시도 및 구현 게시 다른 사람 –

1

한 가지 방법으로 감소 될 것이다

@task 
def recompute_similarity(article_id): 
    article = Article.objects.get(id=article_id) 
    article.is_duplicate = False 
    for other in Article.objects.exclude(id=article_id): 
     if is_similar(article.title, other.title) or is_similar(article.blurb, other.blurb): 
      article.is_duplicate = True 
      break 
    article.save() 

def on_article_save(sender, instance, created, raw, **kwargs): 
    if not raw: 
     recompute_similarity.delay(instance.id) 

signals.post_save.connect(on_article_save, sender=Article) 

이 접근 할 수 있습니다 Haystack와 콘텐츠의 Solr 인덱스를 유지하기 위해, 다음을 위해 SOLR 검색 각 기사에서 일치 한 다음 is_similar 함수에 각각의 상위 일치를 공급합니다. 비슷한 기사를 찾기 위해 전체 데이터 세트를 검색하지 않아도 성능면에서 큰 차이가 있습니다.

+0

응답 주셔서 감사합니다, 나는 이것을 구현하려고합니다. –

관련 문제