Elasticsearch Python Django: Как ограничить содержимое выводимого текста и выделить вводимое ключевое слово
Это моя функция поиска в views.py
def search(request, pk, slug):
es = Elasticsearch()
es_client = Elasticsearch(['http://127.0.0.1:9200'])
print('called search')
search_text = request.GET.get('qq')
print('Search text: {}'.format(search_text))
print('cluster id/ ealstic search index: {}'.format(pk))
s = None
count = 0
try:
if search_text:
s = Search(index=str(pk)).using(es_client).query("match", content=search_text)
response = s.execute()
count = 0
for hit in s:
count += 1
print(str(count) + ' - ' + str(hit.currnet_url))
#print(hit.content)
else:
print('nothing more found')
else:
print('No text to search')
except Exception as e:
count = 0
print('Exception caught')
msg = 'Cluster is not ready to be searched'
return render(request, 'base_app/cluster_search.html', {'warning':msg, 'count':count})
return render(request, 'base_app/cluster_search.html', {'cluster':slug, 'hits':s, 'count':count})
Вот как я индексирую данные в Elasticsearch.
def elastic_indexer(text, depth, url, clusrer_id):
es_client = Elasticsearch(['http://127.0.0.1:9200'])
doc = {
"date": time.strftime("%Y-%m-%d"),
"currnet_url": url,
"depth": depth,
"content": text
}
res = es_client.index(index= str(clusrer_id), doc_type="_doc", body=doc)
print(res["result"])
Это шаблон фронтенда, где пользователи вводят текст для поиска.
{% extends "account/base.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block head_title %}{% trans "Search" %}{% endblock %}
{% block content %}
<a href="{% url 'clusters' %}">Go Back</a>
<P style="font-size:17px;">You are searching in {{cluster.title}}</P>
<form method="GET" action="">
{% csrf_token %}
<button class="btn btn-primary" action="">Search</button>
<input id="q" name="qq" type="text" placeholder="enter search text here" style="width: 500px;">
</form>
{% if hits %}
<table>
{% for hit in hits %}
<tr>
<td>Hit: <a href="">{{hit.currnet_url}}</a></td>
</tr>
<tr>
<td>Content: {{hit.content}}</a></td>
</tr>
{% empty %}
<h3> No search result found </h3>
{% endfor %}
</table>
{% endif %}
<div class="pagination">
<span class="step-links">
{% if page_obj.has_previous %}
<a href="?page=1">« first</a>
<a href="?page={{ page_obj.previous_page_number }}">previous</a>
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_next %}
<a href="?page={{ page_obj.next_page_number }}">next</a>
<a href="?page={{ page_obj.paginator.num_pages }}">last »</a>
{% endif %}
</span>
</div>
{% endblock %}
Это возвращает все, весь текст, хранящийся в "content", как мне ограничить это только вводимым пользователем текстом и показывать только ограниченное количество символов до и после вводимого текста? и включая выделение вводимого текста? Пожалуйста, помогите мне
Пример: Что он показывает:
*User inputs text, assuming it's "django"*
hits: https://www.djangoproject.com/
Content: all of the scraped text stored in "content"
Что я хочу, чтобы он показывал:
User inputs text, assuming it's "django"
hits: https://www.djangoproject.com/
Content: 10 words before "django" and 10 words after "django"