├── .gitignore ├── LICENSE ├── README.asciidoc ├── initialize ├── restapp └── restserv └── webapp ├── static ├── images └── style.css ├── templates ├── base.html ├── index.html └── results.html └── webserv /.gitignore: -------------------------------------------------------------------------------- 1 | README.html 2 | *.swp 3 | restapp/__pycache__ 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.asciidoc: -------------------------------------------------------------------------------- 1 | PostgreSQL as a full-text search engine 2 | ======================================= 3 | Dan Scott (dan@coffeecode.net) 4 | v1.0, 2013-08-07 5 | 6 | Introduction 7 | ------------ 8 | This application shows how to use PostgreSQL as a full-text search engine. 9 | 10 | It demonstrates a minimal approach, with the understanding that many 11 | applications already use PostgreSQL as a primary data store. With the addition 12 | of an extra column, index, and a trigger to the existing database schema, you 13 | may be able to use PostgreSQL directly for full-text search and avoid the pain 14 | of maintaining a separate search engine such as Solr or Sphinx. 15 | 16 | Overview 17 | -------- 18 | This example is divided into three separate scripts: 19 | 20 | . `initialize`: creates the database schema and populates it with data 21 | . `restapp/restserv`: starts a REST server to support REST-based queries 22 | of the database, based on the pattern 23 | `http://hostname/search///`. The service returns the 24 | results (if any) in JSON to the caller. 25 | . `webapp/webserv`: starts a Web server with a minimal HTTP interface for 26 | human-entered queries. The queries are directed to the REST server, and 27 | the JSON results are rendered in a crude but easily extensible fashion. 28 | 29 | Dependencies 30 | ------------ 31 | 32 | * A modern version of PostgreSQL; any currently supported version will suffice. 33 | * Python 3.3 or higher 34 | * Flask 0.10 or higher 35 | * py-postgresql 36 | 37 | Setup 38 | ----- 39 | 40 | . Create a virtual environment using `virtualenv`, adjusting the location of 41 | your Python 3 executable as required: 42 | + 43 | [source,bash] 44 | ------------------------------------------------------------------------------ 45 | virtualenv --python=/usr/bin/python3 ~/postgres-fts 46 | # Set your environment to use this virtual Python installation 47 | . ~/postgres-fts/bin/activate 48 | # Install the dependencies 49 | pip install flask 50 | pip install py-postgresql 51 | ------------------------------------------------------------------------------ 52 | + 53 | . Create the PostgreSQL database and a PostgreSQL user. Depending on your 54 | environment, something like the following should work: 55 | + 56 | [source,bash] 57 | ------------------------------------------------------------------------------ 58 | sudo su - postgres 59 | createdb pgfts 60 | # Note the following creates a PostgreSQL superuser, which is probably 61 | # much more permission that you want in production; see the PostgreSQL 62 | # documentation on granting privileges for real. 63 | createuser -s -P fts_user 64 | # Stop being the postgres user 65 | exit 66 | ------------------------------------------------------------------------------ 67 | + 68 | . Create a `~/.pgpass` file that contains the credentials required to access 69 | the new database you just created, per 70 | http://www.postgresql.org/docs/devel/static/libpq-pgpass.html. 71 | This may look something like: 72 | + 73 | ------------------------------------------------------------------------------ 74 | #hostname:port:database:username:password 75 | localhost:*:pgfts:fts_user:mysecretssss 76 | ------------------------------------------------------------------------------ 77 | + 78 | . Test your connection to the database using the `psql` command. 79 | If the connection fails, you may need to modify `pg_hba.conf` to allow 80 | TCP/IP connections to your database with `md5` authentication. 81 | + 82 | -------------------------------------------------------------------------------- 83 | psql -h localhost -p 5432 -U fts_user -d pgfts 84 | -------------------------------------------------------------------------------- 85 | + 86 | . Modify the constants in `initialize`, `restapp/restserv`, and 87 | `webapp/webserv`, if necessary, to reflect the required PostgreSQL connection 88 | information. 89 | . Create and populate the database schema: 90 | + 91 | ------------------------------------------------------------------------------ 92 | . ~/postgres-fts/bin/activate 93 | ./initialize 94 | ------------------------------------------------------------------------------ 95 | + 96 | . Start up the REST server. The REST server runs on localhost port 8001 by 97 | default; you can change the `PORT` constant to tell it to run elsewhere: 98 | + 99 | [source,bash] 100 | ------------------------------------------------------------------------------ 101 | . ~/postgres-fts/bin/activate 102 | ./restapp/restserv 103 | ------------------------------------------------------------------------------ 104 | + 105 | . The Web server runs on localhost port 5000 by default, and expects to find 106 | the REST server running on localhost port 8001. Change PORT and JSON_HOST 107 | respectively if necessary, then start the Web server: 108 | + 109 | [source,bash] 110 | ------------------------------------------------------------------------------ 111 | . ~/postgres-fts/bin/activate 112 | ./webapp/webserv 113 | ------------------------------------------------------------------------------ 114 | + 115 | . Open http://localhost:5000 in your Web browser (assuming you are using the 116 | defaults) and test it out. Searching for "trees", "sketching", or 117 | "schema.org" should return results! 118 | 119 | Further reading 120 | --------------- 121 | PostgreSQL is capable of much, much more, including language-specific support, 122 | custom dictionaries, boolean operators, wildcard searching, and relevancy 123 | ranking configuration. 124 | 125 | * http://postgresql.org/docs/devel/static/textsearch.html[Official PostgreSQL 126 | documentation] 127 | * http://coffeecode.net/archives/260-Seek-and-ye-shall-find-full-text-search-in-PostgreSQL.html[PostgresOpen 128 | 2012 introduction to full-text search] 129 | 130 | Flask is a powerful Web framework that includes simple mapping of routes to 131 | functions and the jinja2 template system. 132 | 133 | * http://flask.pocoo.org/docs[Official Flask documentation] 134 | * http://jinja.pocoo.org/docs[Official Jinja2 documentation] 135 | 136 | TODO 137 | ---- 138 | 139 | * Demonstrate the use of a parser to support more complex queries (including 140 | booleans and wildcard support) 141 | 142 | License 143 | ------- 144 | 145 | Copyright 2013 Dan Scott, dscott@laurentian.ca 146 | 147 | Licensed under the Apache License, Version 2.0 (the "License"); 148 | you may not use this file except in compliance with the License. 149 | You may obtain a copy of the License at 150 | 151 | http://www.apache.org/licenses/LICENSE-2.0 152 | 153 | Unless required by applicable law or agreed to in writing, software 154 | distributed under the License is distributed on an "AS IS" BASIS, 155 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 156 | See the License for the specific language governing permissions and 157 | limitations under the License. 158 | -------------------------------------------------------------------------------- /initialize: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Create and populate a minimal PostgreSQL schema for full text search 4 | """ 5 | 6 | import postgresql 7 | 8 | DB_NAME = 'pgfts' 9 | DB_HOST = 'localhost' # Uses a local socket 10 | DB_USER = 'fts_user' 11 | 12 | DB = postgresql.open(host=DB_HOST, database=DB_NAME, user=DB_USER) 13 | 14 | def load_db(): 15 | """Add sample data to the database""" 16 | 17 | ins = DB.prepare(""" 18 | INSERT INTO fulltext_search (doc) 19 | VALUES ($1) 20 | """) 21 | ins('Sketching the trees') 22 | ins('Found in schema.org') 23 | ins('Sketched out in schema.org') 24 | ins('Girl on a train') 25 | 26 | def init_db(): 27 | """Initialize our database""" 28 | DB.execute("DROP TABLE IF EXISTS fulltext_search") 29 | DB.execute(""" 30 | CREATE TABLE fulltext_search (id SERIAL, doc TEXT, tsv TSVECTOR) 31 | """) 32 | DB.execute(""" 33 | CREATE TRIGGER tsvupdate BEFORE INSERT OR UPDATE ON fulltext_search 34 | FOR EACH ROW EXECUTE PROCEDURE 35 | tsvector_update_trigger(tsv, 'pg_catalog.english', doc) 36 | """) 37 | DB.execute("CREATE INDEX fts_idx ON fulltext_search USING GIN(tsv)") 38 | 39 | if __name__ == "__main__": 40 | init_db() 41 | load_db() 42 | -------------------------------------------------------------------------------- /restapp/restserv: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Serve up search results as JSON via REST requests 4 | 5 | Provide JSON results including the ID and the search snippet for given search 6 | requests. 7 | 8 | Ultimately needs to support advanced search as well, including NOT operators 9 | and wildcards. 10 | """ 11 | 12 | import json 13 | import postgresql 14 | import flask 15 | import urllib.parse 16 | 17 | app = flask.Flask(__name__) 18 | 19 | # Port on which JSON should be served up 20 | PORT = 8001 21 | 22 | # Database connection info 23 | DB_NAME = 'pgfts' 24 | DB_HOST = 'localhost' 25 | DB_USER = 'fts_user' 26 | 27 | DB = postgresql.open(host=DB_HOST, database=DB_NAME, user=DB_USER) 28 | 29 | @app.route("/search//") 30 | @app.route("/search//") 31 | @app.route("/search///") 32 | def search(query, page=0, limit=10): 33 | """Return JSON formatted search results, including snippets and facets""" 34 | 35 | query = urllib.parse.unquote(query) 36 | results = __get_ranked_results(query, limit, page) 37 | count = __get_result_count(query) 38 | 39 | resj = json.dumps({ 40 | 'query': query, 41 | 'results': results, 42 | 'meta': { 43 | 'total': count, 44 | 'page': page, 45 | 'limit': limit, 46 | 'results': len(results) 47 | } 48 | }) 49 | return flask.Response(response=str(resj), mimetype='application/json') 50 | 51 | def __get_ranked_results(query, limit, page): 52 | """Simple search for terms, with optional limit and paging""" 53 | 54 | sql = """ 55 | WITH q AS (SELECT plainto_tsquery($1) AS query), 56 | ranked AS ( 57 | SELECT id, doc, ts_rank(tsv, query) AS rank 58 | FROM fulltext_search, q 59 | WHERE q.query @@ tsv 60 | ORDER BY rank DESC 61 | LIMIT $2 OFFSET $3 62 | ) 63 | SELECT id, ts_headline(doc, q.query, 'MaxWords=75,MinWords=25,ShortWord=3,MaxFragments=3,FragmentDelimiter="||||"') 64 | FROM ranked, q 65 | ORDER BY ranked DESC 66 | """ 67 | 68 | cur = DB.prepare(sql) 69 | results = [] 70 | for row in cur(query, limit, page*limit): 71 | results.append({ 72 | 'id': row[0], 73 | 'snippets': row[1].split('||||') 74 | }) 75 | 76 | return results 77 | 78 | def __get_result_count(query): 79 | """Gather count of matching results""" 80 | 81 | sql = """ 82 | SELECT COUNT(*) AS rescnt 83 | FROM fulltext_search 84 | WHERE plainto_tsquery($1) @@ tsv 85 | """ 86 | cur = DB.prepare(sql) 87 | count = cur.first(query) 88 | return count 89 | 90 | if __name__ == "__main__": 91 | app.debug = True 92 | app.run(port=PORT) 93 | -------------------------------------------------------------------------------- /webapp/static/images: -------------------------------------------------------------------------------- 1 | ../../data/images -------------------------------------------------------------------------------- /webapp/static/style.css: -------------------------------------------------------------------------------- 1 | h1 { 2 | font-size: 1em; 3 | } 4 | form#search-terms { 5 | display: inline-block; 6 | width: 500px; 7 | vertical-align: top; 8 | } 9 | 10 | /* 11 | form#search-terms label, form#search-terms input { 12 | font-size: 1.5em; 13 | } 14 | */ 15 | 16 | form#search-terms div { 17 | display: inline-block; 18 | } 19 | 20 | h3.restitle { 21 | margin-bottom: 0px; 22 | } 23 | h3.restitle a { 24 | text-decoration: none; 25 | } 26 | .thumb { 27 | display: inline-block; 28 | width: 110px; 29 | vertical-align: top; 30 | } 31 | .result-hdr { 32 | display: none; 33 | vertical-align: top; 34 | width: 100px; 35 | } 36 | .snippets { 37 | display: inline-block; 38 | vertical-align: top; 39 | } 40 | .ressnip { 41 | max-width: 400px; 42 | border-radius: 10px; 43 | padding: 1em; 44 | border: thin black solid; 45 | } 46 | .ressnip { 47 | border-width: thin thin thick thin; 48 | border-style: solid solid double solid; 49 | } 50 | .hidden { 51 | display: none; 52 | } 53 | p.show_hide { 54 | text-align: center; 55 | margin-top: 0em; 56 | margin-bottom: 0.5em; 57 | } 58 | p.show_hide a { 59 | color: rgb(0, 0, 238); 60 | border-top: none; 61 | border-left: thin solid black; 62 | border-right: thin solid black; 63 | border-bottom: thin solid black; 64 | border-bottom-left-radius: 5px; 65 | border-bottom-right-radius: 5px; 66 | padding-left: 1em; 67 | padding-right: 1em; 68 | } 69 | -------------------------------------------------------------------------------- /webapp/templates/base.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | {% block head %} 7 | PostgreSQL full-text search{% block title %}{% endblock %} 8 | 9 | 10 | {% endblock %} 11 | 12 | 13 |

PostgreSQL full-text search{% block heading %}{% endblock %}

14 | {% block content %}{% endblock %} 15 | 16 | 17 | -------------------------------------------------------------------------------- /webapp/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends "base.html" %} 2 | {% block title %} - Welcome{% endblock %} 3 | {% block heading %} - Welcome{% endblock %} 4 | {% block content %} 5 |
6 |
7 | 8 | 15 |
16 |
17 |
18 | {% endblock %} 19 | -------------------------------------------------------------------------------- /webapp/templates/results.html: -------------------------------------------------------------------------------- 1 | {% extends "index.html" %} 2 | {% macro makeurl(query, page=0, limit=10) %} 3 | {% set url = request.base_url ~ "?query=" ~ terms %} 4 | {% if page != 0 %} 5 | {% set url = url ~ "&page=" ~ page %} 6 | {% endif %} 7 | {% if limit and limit != 10 %} 8 | {% set url = url ~ "&limit=" ~ limit %} 9 | {% endif %} 10 | {{ url }} 11 | {%- endmacro %} 12 | {% block title %} - Search Results{% endblock %} 13 | {% block heading %} - Search Results{% endblock %} 14 | {% block content %} 15 | {{ super() }} 16 | 52 |
53 | {% if results.meta.page == 0 and results.meta.total > results.meta.limit %} 54 |

Showing 1 - {{ results.meta.limit }} of about {{ results.meta.total }} results 55 | {% elif results.meta.page == 0 %} 56 |

Showing 1 - {{ results.meta.total }} of about {{ results.meta.total }} results 57 | {% elif (results.meta.page + 1) * results.meta.limit > results.meta.total %} 58 |

Showing {{ (results.meta.page * results.meta.limit) + 1 }} - {{ 59 | results.meta.total }} 60 | of about {{ results.meta.total }} results 61 | {% else %} 62 |

Showing {{ (results.meta.page * results.meta.limit) + 1 }} - {{ 63 | (results.meta.page + 1) * results.meta.limit }} 64 | of about {{ results.meta.total }} results 65 | {% endif %} 66 | {% if results.meta.page > 0 %} 67 | Previous 68 | {% endif %} 69 | {% if ((results.meta.page + 1) * results.meta.limit) < results.meta.total %} 70 | Next 71 | {% endif %} 72 |

73 |
74 |
75 |
76 | {% for result in results['results'] %} 77 |
78 |

Result # {{ result['id'] }}

79 |
80 | {% for snippet in result['snippets'] %} 81 | {% if loop.first %} 82 |
... {{ snippet }} ...
83 | {% else %} 84 | 85 | {% endif %} 86 | {% if loop.last and not loop.first %} 87 |

+

88 | {% endif %} 89 | {% endfor %} 90 |
91 |
92 | {% endfor %} 93 |
94 |
95 | {% endblock %} 96 | -------------------------------------------------------------------------------- /webapp/webserv: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | Simple search UI for PostgreSQL full-text search 4 | """ 5 | 6 | import json 7 | import flask 8 | import os 9 | import urllib.parse, urllib.request 10 | from jinja2 import Environment, FileSystemLoader 11 | 12 | JSON_HOST = "http://localhost:8001" # Where the restserv service is running 13 | 14 | env = Environment(loader=FileSystemLoader(searchpath="%s/templates" % os.path.dirname((os.path.realpath(__file__)))), trim_blocks=True) 15 | app = flask.Flask(__name__) 16 | 17 | @app.route("/") 18 | def index(): 19 | """Serve up the basic search page""" 20 | template = env.get_template('index.html') 21 | return(template.render()) 22 | 23 | @app.route("/search") 24 | def search(): 25 | """Simple search for terms, with optional limit and paging""" 26 | query = flask.request.args.get('query', '') 27 | page = flask.request.args.get('page', '') 28 | jsonu = u"%s/search/%s/" % (JSON_HOST, urllib.parse.quote_plus(query.encode('utf-8'))) 29 | if page: 30 | jsonu = u"%s%d" % (jsonu, int(page)) 31 | res = json.loads(urllib.request.urlopen(jsonu).read().decode('utf-8')) 32 | template = env.get_template('results.html') 33 | return(template.render( 34 | terms=res['query'].replace('+', ' '), 35 | results=res, 36 | request=flask.request 37 | )) 38 | 39 | if __name__ == "__main__": 40 | app.debug = True 41 | print(JSON_HOST) 42 | app.run() 43 | --------------------------------------------------------------------------------