如何在Flask中输出Elasticsearch查询脚本的运行结果?
Hey there! I see you've got a basic setup for querying Elasticsearch with Flask, but you're stuck on how to output the results. Let's break this down into two common scenarios—running as a command-line script and exposing it as a web endpoint—since you're using Flask, both might be useful for you.
问题分析
First off, your current elastic_search function uses input(text) which works for command-line prompts, but in a Flask app, we usually handle input via web requests instead. Also, you're returning the res object, but you haven't added code to actually display or send that result anywhere.
方案1:命令行脚本输出结果
If you just want to run this directly in your terminal and see the results, you can modify the script to print the formatted Elasticsearch response:
from flask import Flask from elasticsearch import Elasticsearch import json app = Flask(__name__) def elastic_search(text): es = Elasticsearch(['10.0.0.9:9200', '10.0.0.15:9200']) word = input(text) # 执行搜索 res = es.search( index="pastebin-*", doc_type='doc', body={"query": {"bool": {"must": [{"match": {"key": word}}]}}} ) return res # 调用函数并打印格式化后的结果 if __name__ == "__main__": search_result = elastic_search("请输入要搜索的关键词: ") # 用json.dumps让输出更易读 print(json.dumps(search_result, indent=2, ensure_ascii=False))
Note: We use json.dumps here to pretty-print the Elasticsearch response, which is way easier to parse than the raw object output.
方案2:Flask Web接口返回结果
Since you're using Flask, it makes sense to turn this into a web endpoint that accepts user input via a request and returns the search results as JSON. Here's how to do that:
from flask import Flask, request, jsonify from elasticsearch import Elasticsearch app = Flask(__name__) def elastic_search(word): es = Elasticsearch(['10.0.0.9:9200', '10.0.0.15:9200']) res = es.search( index="pastebin-*", doc_type='doc', body={"query": {"bool": {"must": [{"match": {"key": word}}]}}} ) return res # 创建GET请求路由,通过URL参数接收关键词 @app.route('/search', methods=['GET']) def search_endpoint(): # 从请求参数中获取关键词,示例:/search?word=your_keyword word = request.args.get('word') if not word: return jsonify({"error": "请提供搜索关键词,例如:/search?word=test"}), 400 # 调用搜索函数并返回JSON结果 result = elastic_search(word) return jsonify(result) if __name__ == "__main__": app.run(debug=True)
使用方法:
- 运行脚本,Flask会启动本地服务(默认地址
http://127.0.0.1:5000) - 在浏览器或API工具中访问:
http://127.0.0.1:5000/search?word=你要搜索的关键词 - 你会直接看到格式化后的Elasticsearch搜索结果以JSON形式返回
内容的提问来源于stack exchange,提问作者point5

