python - 在 Flask 中实现 MongoDB 搜索引擎 API

标签 python json mongodb full-text-search flask-restful

我是 MongoDB 新手,我正在尝试在 Flask 中使用 MongoDB 构建一个简单的搜索页面。

我有一个 restaurants.json 摄取到 MongoDB 中:

{ "_id" : ObjectId("57506d62f57802807471dd42"), "name" : "456 Cookies Shop", "contact" : { "phone" : "604-555-0149", "email" : "456CookiesShop@example.org", "location" : [ -73.8850023, 40.7494272 ] }, "stars" : 4, "categories" : [ "Bakery", "Cookies", "Cake", "Coffee" ] }
{ "_id" : ObjectId("57506d62f57802807471dd28"), "name" : "XYZ Bagels Restaurant", "contact" : { "phone" : "435-555-0190", "email" : "XYZBagelsRestaurant@example.net", "location" : [ -74.0707363, 40.59321569999999 ] }, "stars" : 4, "categories" : [ "Bagels", "Sandwiches", "Coffee" ] }
{ "_id" : ObjectId("57506d62f57802807471dd44"), "name" : "XYZ Steak Buffet", "contact" : { "phone" : "229-555-0197", "email" : "XYZSteakBuffet@example.org", "location" : [ -73.9799932, 40.7660886 ] }, "stars" : 3, "categories" : [ "Steak", "Salad", "Chinese" ] }

search.py​​:

from flask import Flask, render_template, url_for, request, session, redirect, jsonify
import json
from flask import Flask
from flask_pymongo import PyMongo
from pymongo import MongoClient

app = Flask(__name__)
client = MongoClient('localhost',27017)
mongo = PyMongo(app)
db = client.dummy
collection = db.restaurants

@app.route('/search', methods = ['GET'])
def search():
    search = mongo.db.collection
    output = []
    for q in search.find():
        output.append({'name' : q['name'], 'categories' : q['categories']})
    return jsonify({'result' : output})

@app.route('/search/<name>', methods = ['GET'])
def search_by_keyword(name):
    search_by_keyword = mongo.db.collection
    q = search_by_keyword.find_one({'name' : name})
    output = {'name' : q['name']}

    return jsonify({'results' : output})

if __name__ == '__main__':
app.run(debug=True)

search.html:

{% from "_formhelpers.html" import render_field %}
<form method=post>
  <dl>
    {{ render_field(form.select) }}
    <p>
    {{ render_field(form.search) }}
  </dl>
  <p><input type=submit value=Search>
</form>

forms.py:

from wtforms import Form, StringField, SelectField

class SearchForm(Form):
    choices = [('name', 'name'),
           ('categories', 'categories')]
    select = SelectField('Search:', choices = choices)
    search = StringField('')
  • 如何进行关键字搜索以搜索所有 Mongo 字段,而不仅仅是我指定的字段(名称)?
  • 如何将 json 输出文件作为 html 搜索结果发布?

最佳答案

您需要在您感兴趣的字段或使用通配符*的所有字段上创建text索引

名称类别上创建索引

db.restaurants.ensureIndex({"name" : "text", "categories" : "text"})

在所有字段上创建索引*

db.restaurants.ensureIndex( { "$**": "text" } )

搜索字符串

> db.restaurants.find({$text : {$search : "XYZ", $caseSensitive : false}})
{ "_id" : ObjectId("57506d62f57802807471dd44"), "name" : "XYZ Steak Buffet", "contact" : { "phone" : "229-555-0197", "email" : "XYZSteakBuffet@example.org", "location" : [ -73.9799932, 40.7660886 ] }, "stars" : 3, "categories" : [ "Steak", "Salad", "Chinese" ] }
{ "_id" : ObjectId("57506d62f57802807471dd28"), "name" : "XYZ Bagels Restaurant", "contact" : { "phone" : "435-555-0190", "email" : "XYZBagelsRestaurant@example.net", "location" : [ -74.0707363, 40.59321569999999 ] }, "stars" : 4, "categories" : [ "Bagels", "Sandwiches", "Coffee" ] }

搜索categories数组中的字符串

> db.restaurants.find({$text : {$search : "Chinese", $caseSensitive : false}})
{ "_id" : ObjectId("57506d62f57802807471dd44"), "name" : "XYZ Steak Buffet", "contact" : { "phone" : "229-555-0197", "email" : "XYZSteakBuffet@example.org", "location" : [ -73.9799932, 40.7660886 ] }, "stars" : 3, "categories" : [ "Steak", "Salad", "Chinese" ] }
> 

可以使用返回的json在页面中渲染

Mongo Text Index Doc

Text search usage

显示索引

> db.restaurants.getIndexes()
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "bitcoin.restaurants"
    },
    {
        "v" : 2,
        "key" : {
            "_fts" : "text",
            "_ftsx" : 1
        },
        "name" : "name_text_categories_text",
        "ns" : "bitcoin.restaurants",
        "weights" : {
            "categories" : 1,
            "name" : 1
        },
        "default_language" : "english",
        "language_override" : "language",
        "textIndexVersion" : 3
    }

关于python - 在 Flask 中实现 MongoDB 搜索引擎 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48236087/

相关文章:

php - 使用 json 文件或其他方法来缓存数据库条目?

node.js - 使用 mongoose 在 mongodb 中存储文件

python - 如何创建只有一个帖子的页面?

python - RequestHandler 是否有相当于 python 的 Finalize() 调用?

python - 如何使用 Selenium 抓取页面?

Android Spring Rest 客户端 "exchange"创建类(406 Not Acceptable )

python - 如何在一个文件中 Pickle 多个对象?

javascript - 从 ejs View 获取 JSON 数据到 Controller

mysql json vs mongo - 存储空间

mongodb - mongodb 存储文档元数据