0

我正在爲我擁有的文章列表構建一個搜索引擎。我被很多人建議使用彈性搜索進行全文搜索。我寫了下面的代碼。有用。但我有幾個問題。ElasticSearch和Python - 正確的方法

1)如果同一篇文章被添加兩次 - 即indexdoc對同一篇文章運行兩次,它會接受它並添加文章兩次。有沒有辦法在搜索索引中擁有「唯一鍵」?

2)如何更改評分/排名功能?我想更重視標題?

3)這是否正確的方式來做到這一點?

4)如何顯示相關結果 - 如果有拼寫錯誤?

from elasticsearch import Elasticsearch 
from crsq.models import ArticleInfo 

es = Elasticsearch() 

def indexdoc(articledict): 

     doc = { 
       'text': articledict['articlecontent'], 
       'title' : articledict['articletitle'], 
       'url': articledict['url'] 
     } 

     res = es.index(index="article-index", doc_type='article', body=doc) 


def searchdoc(keywordstr): 
     res = es.search(index="article-index", body={"query": {"query_string": {"query": keywordstr}}}) 
     print("Got %d Hits:" % res['hits']['total']) 
     for hit in res['hits']['hits']: 
      print("%(url)s: %(text)s" % hit["_source"]) 

def indexurl(url): 

     articledict = ArticleInfo.objects.filter(url=url).values() 
     if len(articledict): 
       indexdoc(articledict) 
     return 

回答

1

1)您必須爲您的文檔指定一個id。你必須添加參數id當你索引

res = es.index(index="article-index", doc_type='article', body=doc, id="some_unique_id") 

2)還有就是要做到這一點的方法不止一種,但例如,你可以通過改變一點你的查詢提振標題:

{"query": {"query_string": {"query": keywordstr, "fields" : ["text", "title^2"]}} 

有了這個變化title將有重要性的兩倍

3)作爲概念證明並不差。

4)這是一個很大的話題,我想你應該檢查文檔suggesters