在Django应用启动时自动创建Elasticsearch索引

时间:2019-10-11 21:31:30

标签: python django elasticsearch automation startup

我想在启动时自动检查并创建(如果不存在)我的应用程序的Elasticsearch索引,这是我目前无法使用的情况:

echo "Checking if Elasticsearch index is setup"
{
cat <<EOF | python /manage.py shell
from elasticsearch import Elasticsearch
HOST_URLS = ["elasticsearch:9200"]
es_conn = Elasticsearch(HOST_URLS)
INDEX_NAME = "posts"
res = es_conn.indices.exists(index=INDEX_NAME)

if res == True:
  print("Elasicsearch index seems already setup, skipping")
else:
  print("Elasicsearch index not setup yet, creating ...")
  import subprocess
  subprocess.Popen("y | python manage.py search_index --rebuild", shell=True, stdout=subprocess.PIPE).communicate()[
                0].decode('utf-8').strip()
EOF
}>/dev/null

再次导致:

  

“'{}”索引是什么?[n / Y]:“ .format(”,“ .join(index_names)))
  | EOFError:读取行时出现EOF

python manage.py search_index --rebuild来自:https://github.com/sabricot/django-elasticsearch-dsl/

1 个答案:

答案 0 :(得分:0)

我在运行该命令时遇到了同样的问题,当我尝试手动运行时,我意识到它提示询问

Are you sure you want to delete the 'clubs' indexes? [n/Y]:

这意味着当它自动运行时,没有得到使所有事情崩溃的答案。您需要在命令的末尾添加-f标志,这基本上只会从询问此提示时绕过它。例如: python manage.py search_index --rebuild -f