├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── bin ├── index └── search ├── config ├── mappings │ ├── de-analyzer.json │ ├── lang-per-field.json │ └── lang-per-index.json └── pipelines │ ├── lang-per-field.json │ └── lang-per-index.json ├── examples ├── olympics.txt ├── simluate-concatenation.txt ├── simulate-basic.out.json ├── simulate-basic.txt ├── simulate-concatenation.out.json ├── simulate-lang-per-field.out.json ├── simulate-lang-per-field.txt ├── simulate-lang-per-index.out.json └── simulate-lang-per-index.txt └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | /venv/ 2 | /data/ 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: clean init data 2 | 3 | WILI_DIR = data/WiLI-2018 4 | WILI_ZIP_FILE = wili-2018.zip 5 | WILI_DATA_FILE = x_train.txt 6 | 7 | venv/bin/activate: 8 | rm -rf venv/ 9 | python3 -m venv venv 10 | 11 | $(WILI_DIR)/$(WILI_ZIP_FILE): 12 | mkdir -p $(WILI_DIR) 13 | wget -O $(WILI_DIR)/$(WILI_ZIP_FILE) https://zenodo.org/record/841984/files/$(WILI_ZIP_FILE)?download=1 14 | 15 | $(WILI_DIR)/$(WILI_DATA_FILE): $(WILI_DIR)/$(WILI_ZIP_FILE) 16 | unzip -d $(WILI_DIR) $< 17 | 18 | data: $(WILI_DIR)/$(WILI_DATA_FILE) 19 | 20 | .PHONY: clean 21 | clean: 22 | rm -rf data/ venv/ 23 | 24 | .PHONY: init 25 | init: venv/bin/activate 26 | . venv/bin/activate ; \ 27 | pip install -r requirements.txt 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Demo: Elasticsearch Language Identification 2 | 3 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 4 | 5 | A demo of the Elasticsearch language identification for search use-cases, using the [WiLI-2018 corpus](https://arxiv.org/abs/1801.07779) (or a corpus of your choosing). 6 | 7 | # Setup 8 | 9 | ## Prerequisites 10 | 11 | To run the demo, aside from Elasticsearch, you'll need: 12 | 13 | 1. [Python 3.x](https://www.python.org/downloads/) 14 | 1. Linux/macOS tools: `make` and `wget` 15 | 16 | ## Elasticsearch 17 | 18 | See commands below for details. 19 | 20 | 1. Download and install [Elasticsearch](https://www.elastic.co/downloads/elasticsearch), v7.6 or higher, with the Basic license (default) 21 | 1. Install analysis plugins: [ICU](https://www.elastic.co/guide/en/elasticsearch/plugins/current/analysis-icu.html) `icu`, [Japanese](https://www.elastic.co/guide/en/elasticsearch/plugins/current/analysis-kuromoji.html) `kuromoji`, [Korean](https://www.elastic.co/guide/en/elasticsearch/plugins/current/analysis-nori.html) `nori`, [Chinese](https://www.elastic.co/guide/en/elasticsearch/plugins/current/analysis-smartcn.html) `smartcN` 22 | 1. Install a [German decompounder dictionary](https://github.com/uschindler/german-decompounder) 23 | 24 | ### Installation Commands 25 | 26 | Run the following commands from the base of your Elasticsearch installation. 27 | 28 | Analysis plugins: 29 | 30 | ```bash 31 | bin/elasticsearch-plugin install analysis-icu 32 | bin/elasticsearch-plugin install analysis-kuromoji 33 | bin/elasticsearch-plugin install analysis-nori 34 | bin/elasticsearch-plugin install analysis-smartcn 35 | ``` 36 | 37 | German decompounder dictionaries: 38 | 39 | ```bash 40 | mkdir -p config/analysis/de 41 | cd config/analysis/de 42 | wget https://raw.githubusercontent.com/uschindler/german-decompounder/master/de_DR.xml 43 | wget https://raw.githubusercontent.com/uschindler/german-decompounder/master/dictionary-de.txt 44 | ``` 45 | 46 | ## Environment 47 | 48 | Set up the demo environment using `make all`. This will create a Python virtual environment with the required dependencies and download datasets for the demo. 49 | 50 | For more details, have a look at the targets in the `Makefile`. 51 | 52 | # Demo 53 | 54 | The demo contains two scripts: `bin/index` for indexing and `bin/search` for searching. Use the `--help` option to see instructions and available options for each script. 55 | 56 | ## Indexing 57 | 58 | To index documents for the demo, run `bin/index` either with all documents (default) or you can choose to index a subset of the documents. For the purposes of the following examples, we index just the first 10k documents: `bin/index --max 10000` 59 | 60 | ## Search Examples 61 | 62 | ### German Decompounding 63 | 64 | Due to the way the German language compounds words into larger words, special analysis is required to break them up into constituent parts for searching. Try searching for the term "jahr" (meaning "year") and you will see the results of per-language analysis. 65 | 66 | ``` 67 | # only matching exactly on the term "jahr" 68 | bin/search --strategy default jahr 69 | 70 | # matches: "jahr", "jahre", "jahren", "jahrhunderts", etc. 71 | bin/search --strategy per-field jahr 72 | ``` 73 | 74 | ### Common Term 75 | 76 | Some domains use English or Latin terminology. Trying search for the term "computer". 77 | 78 | ``` 79 | # only matching exactly on the term "computer", but multiple languages are in the results 80 | bin/search --strategy default computer 81 | 82 | # matches compound German words as well: "Computersicherheit" (computer security) 83 | bin/search --strategy per-field computer 84 | ``` 85 | 86 | ### Non-Latin Scripts 87 | 88 | Of course it's easy to see how Latin scripts can work even when just using the default or ICU analyzers. However for non-Latin scripts such as CJK (Chinese/Japanese/Korean), we really don't get any good results. Let's try searching for some common Japanese terms and see how our per-language analysis helps. 89 | 90 | ``` 91 | # standard analyzer gets poor precision and returns irrelevant/non-matching results with "network"/"internet": "网络" 92 | bin/search --strategy default 网络 93 | 94 | # ICU and language-specific analysis gets things right, but note the different scores 95 | bin/search --strategy icu 网络 96 | bin/search --strategy per-field 网络 97 | ``` 98 | 99 | ### Per-Field or Per-Index 100 | 101 | Let's compare the scores of per-field and per-index strategies. Note how sometimes the order is different even if the scores are almost exactly the same. In some cases, this can impact search relevance metrics such as nDCG and precision@k. Choose your strategy accordingly! 102 | 103 | ``` 104 | # English tokens: order unchanged 105 | bin/search --strategy per-field networking 106 | bin/search --strategy per-index networking 107 | 108 | # Mixed-use tokens: order differs (last item) 109 | bin/search --strategy per-field university 110 | bin/search --strategy per-index university 111 | ``` 112 | 113 | # License 114 | 115 | ``` 116 | Copyright 2020 Josh Devins, Elastic NV 117 | 118 | Licensed under the Apache License, Version 2.0 (the "License"); 119 | you may not use this file except in compliance with the License. 120 | You may obtain a copy of the License at 121 | 122 | http://www.apache.org/licenses/LICENSE-2.0 123 | 124 | Unless required by applicable law or agreed to in writing, software 125 | distributed under the License is distributed on an "AS IS" BASIS, 126 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 127 | See the License for the specific language governing permissions and 128 | limitations under the License. 129 | ``` 130 | -------------------------------------------------------------------------------- /bin/index: -------------------------------------------------------------------------------- 1 | #!venv/bin/python 2 | 3 | """ 4 | A script to index documents for the language identification search demo. This 5 | will index the same documents in multiple ways in order to demonstrate the 6 | various indexing and search strategies. By default, this will use the 7 | WiLI-2018 training set corpus. 8 | 9 | Due to duplicate strings in the dataset, it will also calculate a hash of 10 | the text to use as document ID, ensuring no duplicate text is in the index. 11 | In order to ensure that we index the number of requested documents, we will 12 | maintain an in-memory list of index document IDs, which are hashes of the 13 | contents. 14 | """ 15 | 16 | import argparse 17 | import copy 18 | import hashlib 19 | import json 20 | import os 21 | 22 | from elasticsearch import Elasticsearch, helpers 23 | from timeit import default_timer as timer 24 | 25 | ANALYZERS = { 26 | 'de': 'german_custom', 27 | 'en': 'english', 28 | 'ja': 'kuromoji', 29 | 'ko': 'nori', 30 | 'zh': 'smartcn', 31 | } 32 | DEFAULT_CORPUS = os.path.join('data', 'WiLI-2018', 'x_train.txt') 33 | DEFAULT_MAX = None 34 | DEFAULT_URL = 'http://localhost:9200' 35 | STRATEGIES = ['lang-per-field', 'lang-per-index'] 36 | 37 | 38 | class Timer: 39 | def __enter__(self): 40 | self.start = timer() 41 | return self 42 | 43 | def __exit__(self, *args): 44 | self.end = timer() 45 | self.interval = self.end - self.start 46 | 47 | 48 | def file_length(filename): 49 | """ 50 | Count the number of lines in a file. 51 | See: https://gist.github.com/zed/0ac760859e614cd03652#file-gistfile1-py-L48-L49 52 | """ 53 | return sum(1 for _ in open(filename, 'r')) 54 | 55 | 56 | def load_mapping(name): 57 | with open(os.path.join('config', 'mappings', f'{name}.json'), 'r') as f: 58 | return json.load(f) 59 | 60 | 61 | def load_german_analyzer(): 62 | with open(os.path.join('config', 'mappings', 'de-analyzer.json'), 'r') as f: 63 | return json.load(f) 64 | 65 | 66 | def recreate_per_field_index(es): 67 | """Recreates the index settings and mappings for the language per-field strategy.""" 68 | 69 | index = 'lang-per-field' 70 | mapping = load_mapping(index) 71 | 72 | # inject the german analyzer stanza 73 | mapping['settings']['analysis'] = load_german_analyzer()['settings']['analysis'] 74 | 75 | print(f"Recreating index for strategy: {index}") 76 | es.indices.delete(index=index, ignore=404) 77 | es.indices.create(index=index, body=mapping) 78 | 79 | 80 | def recreate_per_index_indices(es): 81 | """Recreates the index settings and mappings for the language per-index strategy.""" 82 | 83 | def create(lang, index, analyzer): 84 | body = copy.deepcopy(mapping) 85 | 86 | if lang == 'de': 87 | # inject the german analyzer stanza 88 | body['settings']['analysis'] = load_german_analyzer()['settings']['analysis'] 89 | 90 | # set the analyzer on the text field based on language of the index 91 | body['mappings']['properties']['contents']['properties']['text']['analyzer'] = analyzer 92 | 93 | print(f" - {index}") 94 | es.indices.delete(index=index, ignore=404) 95 | es.indices.create(index=index, body=body) 96 | 97 | strategy = 'lang-per-index' 98 | mapping = load_mapping(strategy) 99 | print(f"Recreating indices for strategy: {strategy}") 100 | 101 | # create the default index for unsupported languages 102 | create(None, strategy, 'default') 103 | 104 | for lang, analyzer in ANALYZERS.items(): 105 | create(lang, f'{strategy}_{lang}', analyzer) 106 | 107 | 108 | def recreate_pipeline(es, id): 109 | """Recreates a pipeline of the given pipeline ID.""" 110 | def body(): 111 | with open(os.path.join('config', 'pipelines', f'{id}.json'), 'r') as f: 112 | return json.load(f) 113 | 114 | print(f"Recreating pipeline: {id}") 115 | es.ingest.delete_pipeline(id=id, ignore=404) 116 | es.ingest.put_pipeline(id=id, body=body()) 117 | 118 | 119 | def index_docs(es, index, corpus, max_num_docs=None): 120 | """ 121 | Indexes all documents in the corpus to the given index (up to `max`). Indexing will use the pipeline of the same 122 | name as the index. 123 | """ 124 | 125 | def actions(limit): 126 | counter = 0 127 | ids = set() 128 | with open(corpus, 'r') as f: 129 | for line in f: 130 | if max_num_docs and counter >= limit: 131 | break 132 | 133 | # ensure no duplicate documents 134 | id = hashlib.md5(line.encode()).hexdigest() 135 | if id not in ids: 136 | counter += 1 137 | ids.add(id) 138 | yield { 139 | '_index': index, 140 | '_id': id, 141 | 'pipeline': index, 142 | '_source': {'contents': line}, 143 | } 144 | 145 | num_docs = file_length(corpus) 146 | 147 | print(f"Indexing documents into '{index}'") 148 | print(f" - corpus size: {num_docs}") 149 | 150 | if max_num_docs: 151 | max_num_docs = min(max_num_docs, num_docs) 152 | print(f" - number of docs to index: {max_num_docs}") 153 | 154 | with Timer() as t: 155 | # index in bulk with large chunks since the documents are very small, and a big timeout to just get it done 156 | helpers.bulk(es, actions(max_num_docs), chunk_size=10000, request_timeout=600, refresh='wait_for') 157 | print(f" - duration: {t.interval:.04f} sec") 158 | 159 | 160 | def print_statistics(es): 161 | """Prints statistics about all indices.""" 162 | 163 | def p(indices, index): 164 | count = indices[index]['total']['docs']['count'] 165 | print(f" - {index}: {count}") 166 | 167 | stats = es.indices.stats(index='lang-*') 168 | print(f"Index statistics:") 169 | 170 | total = stats['_all']['total']['docs']['count'] 171 | print(f" - total docs: {total}") 172 | 173 | indices = stats['indices'] 174 | p(indices, 'lang-per-field') 175 | p(indices, 'lang-per-index') 176 | for lang in ANALYZERS.keys(): 177 | p(indices, f'lang-per-index_{lang}') 178 | 179 | 180 | def main(): 181 | parser = argparse.ArgumentParser(prog='index') 182 | parser.add_argument('--url', default=DEFAULT_URL, help="An Elasticsearch connection URL, e.g. http://user:secret@localhost:9200") 183 | parser.add_argument('--corpus', default=DEFAULT_CORPUS, help="Corpus to index, in a line delimited plain text file") 184 | parser.add_argument('--max', type=int, default=DEFAULT_MAX, help="The maximum number of corpus documents to index, e.g. 1000") 185 | args = parser.parse_args() 186 | 187 | es = Elasticsearch(args.url) 188 | 189 | recreate_per_field_index(es) 190 | recreate_per_index_indices(es) 191 | 192 | for s in STRATEGIES: 193 | recreate_pipeline(es, s) 194 | 195 | for s in STRATEGIES: 196 | index_docs(es, s, args.corpus, args.max) 197 | 198 | print_statistics(es) 199 | 200 | 201 | if __name__ == "__main__": 202 | main() 203 | -------------------------------------------------------------------------------- /bin/search: -------------------------------------------------------------------------------- 1 | #!venv/bin/python 2 | 3 | """ 4 | A script to search over documents for the language identification search demo. 5 | This will use either of the two main strategies: language per-field or per-index. 6 | """ 7 | 8 | import argparse 9 | import json 10 | 11 | from elasticsearch import Elasticsearch 12 | 13 | DEFAULT_URL = 'http://localhost:9200' 14 | 15 | 16 | def search_by_field(es, field, query): 17 | return es.search('lang-per-field', body={ 18 | 'query': { 19 | 'match': { 20 | field: query 21 | } 22 | } 23 | }) 24 | 25 | 26 | def search_by_fields(es, query): 27 | return es.search('lang-per-field', body={ 28 | 'query': { 29 | 'bool': { 30 | 'must': { 31 | 'multi_match': { 32 | 'query': query, 33 | 'best_fields': True, 34 | 'fields': [ 35 | 'contents.de', 36 | 'contents.en', 37 | 'contents.ja', 38 | 'contents.ko', 39 | 'contents.zh' 40 | ] 41 | }, 42 | 'filter': { 43 | 'term': { 44 | 'contents.supported': True 45 | } 46 | } 47 | } 48 | } 49 | } 50 | }) 51 | 52 | 53 | def search_by_indices(es, query): 54 | return es.search('lang-per-index_*', body={ 55 | 'query': { 56 | 'match': { 57 | 'contents.text': query 58 | } 59 | } 60 | }) 61 | 62 | 63 | def main(): 64 | parser = argparse.ArgumentParser(prog='search') 65 | parser.add_argument('--url', default=DEFAULT_URL, help="An Elasticsearch connection URL, e.g. http://user:secret@localhost:9200") 66 | parser.add_argument('--strategy', required=True, choices=['default', 'icu', 'per-field', 'per-index'], help="Search strategy to use") 67 | parser.add_argument('query', help="Query string to search for") 68 | args = parser.parse_args() 69 | 70 | es = Elasticsearch(args.url) 71 | 72 | if args.strategy == 'default': 73 | print("Searching in 'contents.default' field in 'lang-per-field' index") 74 | results = search_by_field(es, 'contents.default', args.query) 75 | contents_key = 'default' 76 | elif args.strategy == 'icu': 77 | print("Searching in 'contents.default.icu' field in 'lang-per-field' index") 78 | results = search_by_field(es, 'contents.default.icu', args.query) 79 | contents_key = 'default' 80 | elif args.strategy == 'per-field': 81 | print("Searching across 'default.*' fields in 'lang-per-field' index") 82 | results = search_by_fields(es, args.query) 83 | contents_key = 'default' 84 | elif args.strategy == 'per-index': 85 | print("Searching in 'contents.text' field across 'lang-per-index_*' indices") 86 | results = search_by_indices(es, args.query) 87 | contents_key = 'text' 88 | else: 89 | raise Exception(f"Unknown strategy: {args.strategy}") 90 | 91 | print(f"Got {results['hits']['total']['value']} hits") 92 | if results['hits']['hits']: 93 | print(" [no] [id] [score] [lang] > contents") 94 | print(" ------------------------------\n") 95 | for index, hit in enumerate(results['hits']['hits']): 96 | c = hit['_source']['contents'] 97 | print(f" [{index+1:2}] [{hit['_id']}] [{hit['_score']:6.3f}] [{c['language']}] > {c[contents_key]}") 98 | 99 | 100 | if __name__ == "__main__": 101 | main() 102 | -------------------------------------------------------------------------------- /config/mappings/de-analyzer.json: -------------------------------------------------------------------------------- 1 | { 2 | "settings": { 3 | "analysis": { 4 | "filter": { 5 | "german_decompounder": { 6 | "type": "hyphenation_decompounder", 7 | "word_list_path": "analysis/de/dictionary-de.txt", 8 | "hyphenation_patterns_path": "analysis/de/de_DR.xml", 9 | "only_longest_match": true, 10 | "min_subword_size": 4 11 | }, 12 | "german_stemmer": { 13 | "type": "stemmer", 14 | "language": "light_german" 15 | }, 16 | "german_stop": { 17 | "type": "stop", 18 | "stopwords": "_german_" 19 | } 20 | }, 21 | "analyzer": { 22 | "german_custom": { 23 | "type": "custom", 24 | "tokenizer": "standard", 25 | "filter": [ 26 | "lowercase", 27 | "german_decompounder", 28 | "german_normalization", 29 | "german_stemmer", 30 | "german_stop" 31 | ] 32 | } 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /config/mappings/lang-per-field.json: -------------------------------------------------------------------------------- 1 | { 2 | "settings": { 3 | "index": { 4 | "number_of_shards": 1, 5 | "number_of_replicas": 0 6 | } 7 | }, 8 | "mappings": { 9 | "dynamic": "strict", 10 | "properties": { 11 | "contents": { 12 | "properties": { 13 | "language": { 14 | "type": "keyword" 15 | }, 16 | "supported": { 17 | "type": "boolean" 18 | }, 19 | "default": { 20 | "type": "text", 21 | "analyzer": "default", 22 | "fields": { 23 | "icu": { 24 | "type": "text", 25 | "analyzer": "icu_analyzer" 26 | } 27 | } 28 | }, 29 | "en": { 30 | "type": "text", 31 | "analyzer": "english" 32 | }, 33 | "de": { 34 | "type": "text", 35 | "analyzer": "german_custom" 36 | }, 37 | "ja": { 38 | "type": "text", 39 | "analyzer": "kuromoji" 40 | }, 41 | "ko": { 42 | "type": "text", 43 | "analyzer": "nori" 44 | }, 45 | "zh": { 46 | "type": "text", 47 | "analyzer": "smartcn" 48 | } 49 | } 50 | } 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /config/mappings/lang-per-index.json: -------------------------------------------------------------------------------- 1 | { 2 | "settings": { 3 | "index": { 4 | "number_of_shards": 1, 5 | "number_of_replicas": 0 6 | } 7 | }, 8 | "mappings": { 9 | "dynamic": "strict", 10 | "properties": { 11 | "contents": { 12 | "properties": { 13 | "language": { 14 | "type": "keyword" 15 | }, 16 | "text": { 17 | "type": "text", 18 | "analyzer": "default" 19 | } 20 | } 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /config/pipelines/lang-per-field.json: -------------------------------------------------------------------------------- 1 | { 2 | "processors": [ 3 | { 4 | "inference": { 5 | "model_id": "lang_ident_model_1", 6 | "inference_config": { 7 | "classification": {} 8 | }, 9 | "field_mappings": { 10 | "contents": "text" 11 | }, 12 | "target_field": "_ml.lang_ident" 13 | } 14 | }, 15 | { 16 | "rename": { 17 | "field": "contents", 18 | "target_field": "contents.default" 19 | } 20 | }, 21 | { 22 | "rename": { 23 | "field": "_ml.lang_ident.predicted_value", 24 | "target_field": "contents.language" 25 | } 26 | }, 27 | { 28 | "script": { 29 | "lang": "painless", 30 | "source": "ctx.contents.supported = (['de', 'en', 'ja', 'ko', 'zh'].contains(ctx.contents.language))" 31 | } 32 | }, 33 | { 34 | "set": { 35 | "if": "ctx.contents.supported", 36 | "field": "contents.{{contents.language}}", 37 | "value": "{{contents.default}}", 38 | "override": false 39 | } 40 | }, 41 | { 42 | "remove": { 43 | "field": "_ml" 44 | } 45 | } 46 | ] 47 | } 48 | -------------------------------------------------------------------------------- /config/pipelines/lang-per-index.json: -------------------------------------------------------------------------------- 1 | { 2 | "processors": [ 3 | { 4 | "inference": { 5 | "model_id": "lang_ident_model_1", 6 | "inference_config": { 7 | "classification": {} 8 | }, 9 | "field_mappings": { 10 | "contents": "text" 11 | }, 12 | "target_field": "_ml.lang_ident" 13 | } 14 | }, 15 | { 16 | "rename": { 17 | "field": "contents", 18 | "target_field": "contents.text" 19 | } 20 | }, 21 | { 22 | "rename": { 23 | "field": "_ml.lang_ident.predicted_value", 24 | "target_field": "contents.language" 25 | } 26 | }, 27 | { 28 | "set": { 29 | "if": "['de', 'en', 'ja', 'ko', 'zh'].contains(ctx.contents.language)", 30 | "field": "_index", 31 | "value": "{{_index}}_{{contents.language}}", 32 | "override": true 33 | } 34 | }, 35 | { 36 | "remove": { 37 | "field": "_ml" 38 | } 39 | } 40 | ] 41 | } 42 | -------------------------------------------------------------------------------- /examples/olympics.txt: -------------------------------------------------------------------------------- 1 | # Example: https://www.elastic.co/blog/how-to-search-ch-jp-kr-part-3 2 | # Adds CJK indexing and search 3 | 4 | DELETE olympics 5 | 6 | PUT /olympics 7 | { 8 | "settings": { 9 | "index": { 10 | "number_of_shards": 1, 11 | "number_of_replicas": 0 12 | } 13 | }, 14 | "mappings": { 15 | "dynamic": "strict", 16 | "properties": { 17 | "contents": { 18 | "properties": { 19 | "language": { 20 | "type": "keyword" 21 | }, 22 | "supported": { 23 | "type": "boolean" 24 | }, 25 | "default": { 26 | "type": "text", 27 | "analyzer": "default", 28 | "fields": { 29 | "icu": { 30 | "type": "text", 31 | "analyzer": "icu_analyzer" 32 | } 33 | } 34 | }, 35 | "en": { 36 | "type": "text", 37 | "analyzer": "english" 38 | }, 39 | "ja": { 40 | "type": "text", 41 | "analyzer": "kuromoji" 42 | }, 43 | "ko": { 44 | "type": "text", 45 | "analyzer": "nori" 46 | }, 47 | "zh": { 48 | "type": "text", 49 | "analyzer": "smartcn" 50 | }, 51 | "cjk": { 52 | "type": "text", 53 | "analyzer": "cjk" 54 | } 55 | } 56 | } 57 | } 58 | } 59 | } 60 | 61 | DELETE _ingest/pipeline/olympics 62 | 63 | PUT _ingest/pipeline/olympics 64 | { 65 | "processors": [ 66 | { 67 | "pipeline": { 68 | "name": "lang-per-field" 69 | } 70 | }, 71 | { 72 | "script": { 73 | "lang": "painless", 74 | "source": "if (['ja', 'ko', 'zh'].contains(ctx.contents.language)) { ctx.contents.cjk = ctx.contents.default }" 75 | } 76 | } 77 | ] 78 | } 79 | 80 | POST _bulk 81 | { "index" : { "_index" : "olympics", "_id" : "1", "pipeline": "olympics" } } 82 | { "contents": "세계인의 축제, 제23회 동계올림픽대회는 대한민국 강원도 평창에서 2018년 2월 9일부터 25일까지 17일간 개최됩니다. 대한민국 평창은 세 번의 도전 끝에 지난 2011년 7월 6일 열린 제123차 IOC 총회에서 과반 표를 획득하며 2018년 동계올림픽 개최지로 선정되었습니다. 이로써 대한민국에서는 1988년 서울 올림픽 이후 30년 만에, 평창에서 개∙폐회식과 대부분의 설상 경기가 개최되며, 강릉에서는 빙상 종목 전 경기가, 그리고 정선에서는 알파인 스키 활강 경기가 개최될 예정입니다." } 83 | { "index" : { "_index" : "olympics", "_id" : "2", "pipeline": "olympics" } } 84 | { "contents": "The XXIII Olympic Winter Games will be held for 17 days from 9 to 25 February 2018 in PyeongChang, Gangwon Province, the Republic of Korea. PyeongChang was selected as the host city of the 2018 Olympic Winter Games after receiving a majority vote at the 123rd IOC Session held on 6 July 2011 after three consecutive bids. The Olympic Winter Games will be held in Korea for the first time in 30 years after the Seoul Olympic Games in 1988. PyeongChang will be the stage for the Opening and Closing Ceremonies and most snow sports. Alpine speed events will take place in Jeongseon, and all ice sports will be competed in the coastal city of Gangneung." } 85 | { "index" : { "_index" : "olympics", "_id" : "3", "pipeline": "olympics" } } 86 | { "contents": "第23届冬季奥运会将于2018年2月9日-25日在韩国江原道平昌展开。韩国平昌在第三次申奥之后,于2011年7月6日召开的第123届国际奥委会全会上被选定为2018年冬季奥运会的主办地。由此,韩国自1988年举办首尔夏季奥运会以后,时隔30年,将首次举办冬季奥运会。该届冬奥会的开·闭幕式以及大部分的雪上运动将在平昌进行,而所有冰上运动将在江陵、高山滑雪滑降比赛则将在旌善进行。"}PUT /mono/docs/4{ "body" : "世界の人々の祝祭、第23回冬季オリンピック大会は大韓民国江原道平昌で2018年2月9日から25日までの17日間、開催されます。大韓民国・平昌は三度の挑戦の末、2011年7月7日に開かれた第123回IOC総会で過半数票を獲得し、2018年冬季オリンピック及びパラリンピックの開催地に選ばれました。これにより1988年ソウルオリンピック開催後30年の時を経てついに、大韓民国で最初の冬季パラリンピックの舞台が繰り広げられます。平昌で開・閉会式とほぼ全ての雪上競技が開催され、江陵では氷上種目全競技が、そして旌善ではアルペンスキー滑降競技が開催される予定です。" } 87 | { "index" : { "_index" : "olympics", "_id" : "4", "pipeline": "olympics" } } 88 | { "contents": "世界の人々の祝祭、第23回冬季オリンピック大会は大韓民国江原道平昌で2018年2月9日から25日までの17日間、開催されます。大韓民国・平昌は三度の挑戦の末、2011年7月7日に開かれた第123回IOC総会で過半数票を獲得し、2018年冬季オリンピック及びパラリンピックの開催地に選ばれました。これにより1988年ソウルオリンピック開催後30年の時を経てついに、大韓民国で最初の冬季パラリンピックの舞台が繰り広げられます。平昌で開・閉会式とほぼ全ての雪上競技が開催され、江陵では氷上種目全競技が、そして旌善ではアルペンスキー滑降競技が開催される予定です。" } 89 | 90 | # Queries against default analyzer field 91 | ## Korean 92 | GET /olympics/_search 93 | { 94 | "query": { 95 | "match": { 96 | "contents.default": "올림픽대회" 97 | } 98 | } 99 | } 100 | 101 | # English 102 | GET /olympics/_search 103 | { 104 | "query": { 105 | "match": { 106 | "contents.default": "Olympic Games" 107 | } 108 | } 109 | } 110 | 111 | # Japanese 112 | GET /olympics/_search 113 | { 114 | "query": { 115 | "match": { 116 | "contents.default": "オリンピック大会" 117 | } 118 | } 119 | } 120 | 121 | # Chinese 122 | GET /olympics/_search 123 | { 124 | "query": { 125 | "match": { 126 | "contents.default": "奥运会" 127 | } 128 | } 129 | } 130 | 131 | # Queries against ICU analyzer field (not in the example but let's try it out anyways) 132 | ## Korean 133 | GET /olympics/_search 134 | { 135 | "query": { 136 | "match": { 137 | "contents.default.icu": "올림픽대회" 138 | } 139 | } 140 | } 141 | 142 | # English 143 | GET /olympics/_search 144 | { 145 | "query": { 146 | "match": { 147 | "contents.default.icu": "Olympic Games" 148 | } 149 | } 150 | } 151 | 152 | # Japanese 153 | GET /olympics/_search 154 | { 155 | "query": { 156 | "match": { 157 | "contents.default.icu": "オリンピック大会" 158 | } 159 | } 160 | } 161 | 162 | # Chinese 163 | GET /olympics/_search 164 | { 165 | "query": { 166 | "match": { 167 | "contents.default.icu": "奥运会" 168 | } 169 | } 170 | } 171 | 172 | # Queries against script-specififc fields 173 | ## Korean 174 | POST /olympics/_search 175 | { 176 | "query": { 177 | "multi_match": { 178 | "query": "올림픽대회", 179 | "type": "best_fields", 180 | "fields": [ 181 | "contents.en", 182 | "contents.cjk" 183 | ] 184 | } 185 | } 186 | } 187 | 188 | ## English 189 | POST /olympics/_search 190 | { 191 | "query": { 192 | "multi_match": { 193 | "query": "Olympic Games", 194 | "type": "best_fields", 195 | "fields": [ 196 | "contents.en", 197 | "contents.cjk" 198 | ] 199 | } 200 | } 201 | } 202 | 203 | ## Japanese 204 | POST /olympics/_search 205 | { 206 | "query": { 207 | "multi_match": { 208 | "query": "オリンピック大会", 209 | "type": "best_fields", 210 | "fields": [ 211 | "contents.en", 212 | "contents.cjk" 213 | ] 214 | } 215 | } 216 | } 217 | 218 | ## Chinese 219 | POST /olympics/_search 220 | { 221 | "query": { 222 | "multi_match": { 223 | "query": "奥运会", 224 | "type": "best_fields", 225 | "fields": [ 226 | "contents.en", 227 | "contents.cjk" 228 | ] 229 | } 230 | } 231 | } 232 | 233 | # Queries against language-specific fields 234 | ## Korean 235 | POST /olympics/_search 236 | { 237 | "query": { 238 | "multi_match": { 239 | "query": "올림픽대회", 240 | "type": "best_fields", 241 | "fields": [ 242 | "contents.en", 243 | "contents.ja", 244 | "contents.ko", 245 | "contents.zh" 246 | ] 247 | } 248 | } 249 | } 250 | 251 | ## English 252 | POST /olympics/_search 253 | { 254 | "query": { 255 | "multi_match": { 256 | "query": "Olympic Games", 257 | "type": "best_fields", 258 | "fields": [ 259 | "contents.en", 260 | "contents.ja", 261 | "contents.ko", 262 | "contents.zh" 263 | ] 264 | } 265 | } 266 | } 267 | 268 | ## Japanese 269 | POST /olympics/_search 270 | { 271 | "query": { 272 | "multi_match": { 273 | "query": "オリンピック大会", 274 | "type": "best_fields", 275 | "fields": [ 276 | "contents.en", 277 | "contents.ja", 278 | "contents.ko", 279 | "contents.zh" 280 | ] 281 | } 282 | } 283 | } 284 | 285 | ## Chinese 286 | POST /olympics/_search 287 | { 288 | "query": { 289 | "multi_match": { 290 | "query": "奥运会", 291 | "type": "best_fields", 292 | "fields": [ 293 | "contents.en", 294 | "contents.ja", 295 | "contents.ko", 296 | "contents.zh" 297 | ] 298 | } 299 | } 300 | } 301 | -------------------------------------------------------------------------------- /examples/simluate-concatenation.txt: -------------------------------------------------------------------------------- 1 | # simulate concatenating multiple fields into a single temporoary field only for language identification 2 | 3 | POST _ingest/pipeline/_simulate 4 | { 5 | "pipeline": { 6 | "processors": [ 7 | { 8 | "join": { 9 | "field": "topics", 10 | "target_field": "tmp.topics", 11 | "separator": ", " 12 | } 13 | }, 14 | { 15 | "set": { 16 | "field": "tmp.contents", 17 | "value": "{{title}}. {{topics}}. {{body}}" 18 | } 19 | }, 20 | { 21 | "inference": { 22 | "model_id": "lang_ident_model_1", 23 | "inference_config": { 24 | "classification": { 25 | "num_top_classes": 3 26 | } 27 | }, 28 | "field_mappings": { 29 | "tmp.contents": "text" 30 | }, 31 | "target_field": "_ml.lang_ident" 32 | } 33 | }, 34 | { 35 | "rename": { 36 | "field": "_ml.lang_ident.predicted_value", 37 | "target_field": "language.code" 38 | } 39 | }, 40 | { 41 | "script": { 42 | "lang": "painless", 43 | "source": "ctx.language.supported = (['de', 'en', 'ja', 'ko', 'zh'].contains(ctx.language.code))" 44 | } 45 | }, 46 | { 47 | "set": { 48 | "if": "ctx.language.supported", 49 | "field": "body_by_lang.{{language.code}}", 50 | "value": "{{body}}", 51 | "override": false 52 | } 53 | }, 54 | { 55 | "remove": { 56 | "field": ["tmp", "_ml"] 57 | } 58 | } 59 | ] 60 | }, 61 | "docs": [ 62 | { 63 | "_source": { 64 | "title": "The Rain in Spain", 65 | "url": "https://en.wikipedia.org/wiki/The_Rain_in_Spain", 66 | "topics": [ 67 | "Song", 68 | "Movie", 69 | "Soundtrack", 70 | "Musical", 71 | "My Fair Lady" 72 | ], 73 | "body": """"The Rain in Spain" is a song from the musical My Fair Lady, with music by Frederick Loewe and lyrics by Alan Jay Lerner. The song was published in 1956, sounding similar to piano trio in C minor 3rd movement by Josep Suk.""" 74 | } 75 | } 76 | ] 77 | } 78 | -------------------------------------------------------------------------------- /examples/simulate-basic.out.json: -------------------------------------------------------------------------------- 1 | { 2 | "docs" : [ 3 | { 4 | "doc" : { 5 | "_index" : "_index", 6 | "_type" : "_doc", 7 | "_id" : "_id", 8 | "_source" : { 9 | "contents" : "Das leben ist kein Ponyhof", 10 | "_ml" : { 11 | "lang_ident" : { 12 | "top_classes" : [ 13 | { 14 | "class_name" : "de", 15 | "class_probability" : 0.9996006023972855 16 | }, 17 | { 18 | "class_name" : "el-Latn", 19 | "class_probability" : 2.625873919853074E-4 20 | }, 21 | { 22 | "class_name" : "ru-Latn", 23 | "class_probability" : 1.130237050226503E-4 24 | } 25 | ], 26 | "predicted_value" : "de", 27 | "model_id" : "lang_ident_model_1" 28 | } 29 | } 30 | }, 31 | "_ingest" : { 32 | "timestamp" : "2020-01-21T14:38:13.810179Z" 33 | } 34 | } 35 | }, 36 | { 37 | "doc" : { 38 | "_index" : "_index", 39 | "_type" : "_doc", 40 | "_id" : "_id", 41 | "_source" : { 42 | "contents" : "The rain in Spain stays mainly in the plains", 43 | "_ml" : { 44 | "lang_ident" : { 45 | "top_classes" : [ 46 | { 47 | "class_name" : "en", 48 | "class_probability" : 0.9988809847231199 49 | }, 50 | { 51 | "class_name" : "ga", 52 | "class_probability" : 7.764148026288316E-4 53 | }, 54 | { 55 | "class_name" : "gd", 56 | "class_probability" : 7.968926766495827E-5 57 | } 58 | ], 59 | "predicted_value" : "en", 60 | "model_id" : "lang_ident_model_1" 61 | } 62 | } 63 | }, 64 | "_ingest" : { 65 | "timestamp" : "2020-01-21T14:38:13.810185Z" 66 | } 67 | } 68 | }, 69 | { 70 | "doc" : { 71 | "_index" : "_index", 72 | "_type" : "_doc", 73 | "_id" : "_id", 74 | "_source" : { 75 | "contents" : "This is mostly English but has a touch of Latin since we often just say, Carpe diem", 76 | "_ml" : { 77 | "lang_ident" : { 78 | "top_classes" : [ 79 | { 80 | "class_name" : "en", 81 | "class_probability" : 0.9997901768317939 82 | }, 83 | { 84 | "class_name" : "ja", 85 | "class_probability" : 8.756250766054857E-5 86 | }, 87 | { 88 | "class_name" : "fil", 89 | "class_probability" : 1.6980752372837307E-5 90 | } 91 | ], 92 | "predicted_value" : "en", 93 | "model_id" : "lang_ident_model_1" 94 | } 95 | } 96 | }, 97 | "_ingest" : { 98 | "timestamp" : "2020-01-21T14:38:13.810189Z" 99 | } 100 | } 101 | } 102 | ] 103 | } 104 | -------------------------------------------------------------------------------- /examples/simulate-basic.txt: -------------------------------------------------------------------------------- 1 | # simulate a basic inference setup 2 | 3 | POST _ingest/pipeline/_simulate 4 | { 5 | "pipeline": { 6 | "processors": [ 7 | { 8 | "inference": { 9 | "model_id": "lang_ident_model_1", 10 | "inference_config": { 11 | "classification": { 12 | "num_top_classes": 3 13 | } 14 | }, 15 | "field_mappings": { 16 | "contents": "text" 17 | }, 18 | "target_field": "_ml.lang_ident" 19 | } 20 | } 21 | ] 22 | }, 23 | "docs": [ 24 | { 25 | "_source": { 26 | "contents": "Das leben ist kein Ponyhof" 27 | } 28 | }, 29 | { 30 | "_source": { 31 | "contents": "The rain in Spain stays mainly in the plains" 32 | } 33 | }, 34 | { 35 | "_source": { 36 | "contents": "This is mostly English but has a touch of Latin since we often just say, Carpe diem" 37 | } 38 | } 39 | ] 40 | } 41 | -------------------------------------------------------------------------------- /examples/simulate-concatenation.out.json: -------------------------------------------------------------------------------- 1 | { 2 | "docs" : [ 3 | { 4 | "doc" : { 5 | "_index" : "_index", 6 | "_type" : "_doc", 7 | "_id" : "_id", 8 | "_source" : { 9 | "body_by_lang" : { 10 | "en" : """\"The Rain in Spain\" is a song from the musical My Fair Lady, with music by Frederick Loewe and lyrics by Alan Jay Lerner. The song was published in 1956, sounding similar to piano trio in C minor 3rd movement by Josep Suk.""" 11 | }, 12 | "topics" : [ 13 | "Song", 14 | "Movie", 15 | "Soundtrack", 16 | "Musical", 17 | "My Fair Lady" 18 | ], 19 | "language" : { 20 | "code" : "en", 21 | "supported" : true 22 | }, 23 | "title" : "The Rain in Spain", 24 | "body" : """"The Rain in Spain" is a song from the musical My Fair Lady, with music by Frederick Loewe and lyrics by Alan Jay Lerner. The song was published in 1956, sounding similar to piano trio in C minor 3rd movement by Josep Suk.""", 25 | "url" : "https://en.wikipedia.org/wiki/The_Rain_in_Spain" 26 | }, 27 | "_ingest" : { 28 | "timestamp" : "2020-01-23T13:41:12.113321Z" 29 | } 30 | } 31 | } 32 | ] 33 | } 34 | -------------------------------------------------------------------------------- /examples/simulate-lang-per-field.out.json: -------------------------------------------------------------------------------- 1 | { 2 | "docs" : [ 3 | { 4 | "doc" : { 5 | "_index" : "_index", 6 | "_type" : "_doc", 7 | "_id" : "_id", 8 | "_source" : { 9 | "contents" : { 10 | "de" : "Das leben ist kein Ponyhof", 11 | "default" : "Das leben ist kein Ponyhof", 12 | "language" : "de", 13 | "supported" : true 14 | }, 15 | "_ml" : { 16 | "lang_ident" : { 17 | "top_classes" : [ 18 | { 19 | "class_name" : "de", 20 | "class_probability" : 0.9996006023972855 21 | }, 22 | { 23 | "class_name" : "el-Latn", 24 | "class_probability" : 2.625873919853074E-4 25 | }, 26 | { 27 | "class_name" : "ru-Latn", 28 | "class_probability" : 1.130237050226503E-4 29 | } 30 | ], 31 | "model_id" : "lang_ident_model_1" 32 | } 33 | } 34 | }, 35 | "_ingest" : { 36 | "timestamp" : "2020-01-22T12:40:03.218641Z" 37 | } 38 | } 39 | }, 40 | { 41 | "doc" : { 42 | "_index" : "_index", 43 | "_type" : "_doc", 44 | "_id" : "_id", 45 | "_source" : { 46 | "contents" : { 47 | "en" : "The rain in Spain stays mainly in the plains", 48 | "default" : "The rain in Spain stays mainly in the plains", 49 | "language" : "en", 50 | "supported" : true 51 | }, 52 | "_ml" : { 53 | "lang_ident" : { 54 | "top_classes" : [ 55 | { 56 | "class_name" : "en", 57 | "class_probability" : 0.9988809847231199 58 | }, 59 | { 60 | "class_name" : "ga", 61 | "class_probability" : 7.764148026288316E-4 62 | }, 63 | { 64 | "class_name" : "gd", 65 | "class_probability" : 7.968926766495827E-5 66 | } 67 | ], 68 | "model_id" : "lang_ident_model_1" 69 | } 70 | } 71 | }, 72 | "_ingest" : { 73 | "timestamp" : "2020-01-22T12:40:03.218646Z" 74 | } 75 | } 76 | }, 77 | { 78 | "doc" : { 79 | "_index" : "_index", 80 | "_type" : "_doc", 81 | "_id" : "_id", 82 | "_source" : { 83 | "contents" : { 84 | "default" : "オリンピック大会", 85 | "language" : "ja", 86 | "ja" : "オリンピック大会", 87 | "supported" : true 88 | }, 89 | "_ml" : { 90 | "lang_ident" : { 91 | "top_classes" : [ 92 | { 93 | "class_name" : "ja", 94 | "class_probability" : 0.9993823252841599 95 | }, 96 | { 97 | "class_name" : "el", 98 | "class_probability" : 2.6448654791599055E-4 99 | }, 100 | { 101 | "class_name" : "sd", 102 | "class_probability" : 1.4846805271384584E-4 103 | } 104 | ], 105 | "model_id" : "lang_ident_model_1" 106 | } 107 | } 108 | }, 109 | "_ingest" : { 110 | "timestamp" : "2020-01-22T12:40:03.218648Z" 111 | } 112 | } 113 | }, 114 | { 115 | "doc" : { 116 | "_index" : "_index", 117 | "_type" : "_doc", 118 | "_id" : "_id", 119 | "_source" : { 120 | "contents" : { 121 | "default" : "로마는 하루아침에 이루어진 것이 아니다", 122 | "language" : "ko", 123 | "ko" : "로마는 하루아침에 이루어진 것이 아니다", 124 | "supported" : true 125 | }, 126 | "_ml" : { 127 | "lang_ident" : { 128 | "top_classes" : [ 129 | { 130 | "class_name" : "ko", 131 | "class_probability" : 0.9999939196272863 132 | }, 133 | { 134 | "class_name" : "ka", 135 | "class_probability" : 3.0431805047662344E-6 136 | }, 137 | { 138 | "class_name" : "am", 139 | "class_probability" : 1.710514725818281E-6 140 | } 141 | ], 142 | "model_id" : "lang_ident_model_1" 143 | } 144 | } 145 | }, 146 | "_ingest" : { 147 | "timestamp" : "2020-01-22T12:40:03.218649Z" 148 | } 149 | } 150 | }, 151 | { 152 | "doc" : { 153 | "_index" : "_index", 154 | "_type" : "_doc", 155 | "_id" : "_id", 156 | "_source" : { 157 | "contents" : { 158 | "default" : "授人以鱼不如授人以渔", 159 | "language" : "zh", 160 | "zh" : "授人以鱼不如授人以渔", 161 | "supported" : true 162 | }, 163 | "_ml" : { 164 | "lang_ident" : { 165 | "top_classes" : [ 166 | { 167 | "class_name" : "zh", 168 | "class_probability" : 0.9999810103320087 169 | }, 170 | { 171 | "class_name" : "ja", 172 | "class_probability" : 1.0390454083183788E-5 173 | }, 174 | { 175 | "class_name" : "ka", 176 | "class_probability" : 2.6302271562335787E-6 177 | } 178 | ], 179 | "model_id" : "lang_ident_model_1" 180 | } 181 | } 182 | }, 183 | "_ingest" : { 184 | "timestamp" : "2020-01-22T12:40:03.21865Z" 185 | } 186 | } 187 | }, 188 | { 189 | "doc" : { 190 | "_index" : "_index", 191 | "_type" : "_doc", 192 | "_id" : "_id", 193 | "_source" : { 194 | "contents" : { 195 | "default" : "Qui court deux lievres a la fois, n’en prend aucun", 196 | "language" : "fr", 197 | "supported" : false 198 | }, 199 | "_ml" : { 200 | "lang_ident" : { 201 | "top_classes" : [ 202 | { 203 | "class_name" : "fr", 204 | "class_probability" : 0.9999669852240882 205 | }, 206 | { 207 | "class_name" : "gd", 208 | "class_probability" : 2.3485226102079597E-5 209 | }, 210 | { 211 | "class_name" : "ht", 212 | "class_probability" : 3.536708810360631E-6 213 | } 214 | ], 215 | "model_id" : "lang_ident_model_1" 216 | } 217 | } 218 | }, 219 | "_ingest" : { 220 | "timestamp" : "2020-01-22T12:40:03.218652Z" 221 | } 222 | } 223 | }, 224 | { 225 | "doc" : { 226 | "_index" : "_index", 227 | "_type" : "_doc", 228 | "_id" : "_id", 229 | "_source" : { 230 | "contents" : { 231 | "default" : "Lupus non timet canem latrantem", 232 | "language" : "la", 233 | "supported" : false 234 | }, 235 | "_ml" : { 236 | "lang_ident" : { 237 | "top_classes" : [ 238 | { 239 | "class_name" : "la", 240 | "class_probability" : 0.614050940088811 241 | }, 242 | { 243 | "class_name" : "fr", 244 | "class_probability" : 0.32530021315840363 245 | }, 246 | { 247 | "class_name" : "sq", 248 | "class_probability" : 0.03353817054854559 249 | } 250 | ], 251 | "model_id" : "lang_ident_model_1" 252 | } 253 | } 254 | }, 255 | "_ingest" : { 256 | "timestamp" : "2020-01-22T12:40:03.218653Z" 257 | } 258 | } 259 | }, 260 | { 261 | "doc" : { 262 | "_index" : "_index", 263 | "_type" : "_doc", 264 | "_id" : "_id", 265 | "_source" : { 266 | "contents" : { 267 | "en" : "This is mostly English but has a touch of Latin since we often just say, Carpe diem", 268 | "default" : "This is mostly English but has a touch of Latin since we often just say, Carpe diem", 269 | "language" : "en", 270 | "supported" : true 271 | }, 272 | "_ml" : { 273 | "lang_ident" : { 274 | "top_classes" : [ 275 | { 276 | "class_name" : "en", 277 | "class_probability" : 0.9997901768317939 278 | }, 279 | { 280 | "class_name" : "ja", 281 | "class_probability" : 8.756250766054857E-5 282 | }, 283 | { 284 | "class_name" : "fil", 285 | "class_probability" : 1.6980752372837307E-5 286 | } 287 | ], 288 | "model_id" : "lang_ident_model_1" 289 | } 290 | } 291 | }, 292 | "_ingest" : { 293 | "timestamp" : "2020-01-22T12:40:03.218654Z" 294 | } 295 | } 296 | } 297 | ] 298 | } 299 | -------------------------------------------------------------------------------- /examples/simulate-lang-per-field.txt: -------------------------------------------------------------------------------- 1 | # simulate a language per-field and output top 3 language classes for inspection 2 | 3 | POST _ingest/pipeline/_simulate 4 | { 5 | "pipeline": { 6 | "processors": [ 7 | { 8 | "inference": { 9 | "model_id": "lang_ident_model_1", 10 | "inference_config": { 11 | "classification": { 12 | "num_top_classes": 3 13 | } 14 | }, 15 | "field_mappings": { 16 | "contents": "text" 17 | }, 18 | "target_field": "_ml.lang_ident" 19 | } 20 | }, 21 | { 22 | "rename": { 23 | "field": "contents", 24 | "target_field": "contents.default" 25 | } 26 | }, 27 | { 28 | "rename": { 29 | "field": "_ml.lang_ident.predicted_value", 30 | "target_field": "contents.language" 31 | } 32 | }, 33 | { 34 | "script": { 35 | "lang": "painless", 36 | "source": "ctx.contents.supported = (['de', 'en', 'ja', 'ko', 'zh'].contains(ctx.contents.language))" 37 | } 38 | }, 39 | { 40 | "set": { 41 | "if": "ctx.contents.supported", 42 | "field": "contents.{{contents.language}}", 43 | "value": "{{contents.default}}", 44 | "override": false 45 | } 46 | } 47 | ] 48 | }, 49 | "docs": [ 50 | { 51 | "_source": { 52 | "contents": "Das leben ist kein Ponyhof" 53 | } 54 | }, 55 | { 56 | "_source": { 57 | "contents": "The rain in Spain stays mainly in the plains" 58 | } 59 | }, 60 | { 61 | "_source": { 62 | "contents": "オリンピック大会" 63 | } 64 | }, 65 | { 66 | "_source": { 67 | "contents": "로마는 하루아침에 이루어진 것이 아니다" 68 | } 69 | }, 70 | { 71 | "_source": { 72 | "contents": "授人以鱼不如授人以渔" 73 | } 74 | }, 75 | { 76 | "_source": { 77 | "contents": "Qui court deux lievres a la fois, n’en prend aucun" 78 | } 79 | }, 80 | { 81 | "_source": { 82 | "contents": "Lupus non timet canem latrantem" 83 | } 84 | }, 85 | { 86 | "_source": { 87 | "contents": "This is mostly English but has a touch of Latin since we often just say, Carpe diem" 88 | } 89 | } 90 | ] 91 | } 92 | -------------------------------------------------------------------------------- /examples/simulate-lang-per-index.out.json: -------------------------------------------------------------------------------- 1 | { 2 | "docs" : [ 3 | { 4 | "doc" : { 5 | "_index" : "_index_de", 6 | "_type" : "_doc", 7 | "_id" : "_id", 8 | "_source" : { 9 | "contents" : { 10 | "language" : "de", 11 | "text" : "Das leben ist kein Ponyhof" 12 | }, 13 | "_ml" : { 14 | "lang_ident" : { 15 | "top_classes" : [ 16 | { 17 | "class_name" : "de", 18 | "class_probability" : 0.9996006023972855 19 | }, 20 | { 21 | "class_name" : "el-Latn", 22 | "class_probability" : 2.625873919853074E-4 23 | }, 24 | { 25 | "class_name" : "ru-Latn", 26 | "class_probability" : 1.130237050226503E-4 27 | } 28 | ], 29 | "model_id" : "lang_ident_model_1" 30 | } 31 | } 32 | }, 33 | "_ingest" : { 34 | "timestamp" : "2020-01-21T14:41:48.486009Z" 35 | } 36 | } 37 | }, 38 | { 39 | "doc" : { 40 | "_index" : "_index_en", 41 | "_type" : "_doc", 42 | "_id" : "_id", 43 | "_source" : { 44 | "contents" : { 45 | "language" : "en", 46 | "text" : "The rain in Spain stays mainly in the plains" 47 | }, 48 | "_ml" : { 49 | "lang_ident" : { 50 | "top_classes" : [ 51 | { 52 | "class_name" : "en", 53 | "class_probability" : 0.9988809847231199 54 | }, 55 | { 56 | "class_name" : "ga", 57 | "class_probability" : 7.764148026288316E-4 58 | }, 59 | { 60 | "class_name" : "gd", 61 | "class_probability" : 7.968926766495827E-5 62 | } 63 | ], 64 | "model_id" : "lang_ident_model_1" 65 | } 66 | } 67 | }, 68 | "_ingest" : { 69 | "timestamp" : "2020-01-21T14:41:48.486037Z" 70 | } 71 | } 72 | }, 73 | { 74 | "doc" : { 75 | "_index" : "_index_ja", 76 | "_type" : "_doc", 77 | "_id" : "_id", 78 | "_source" : { 79 | "contents" : { 80 | "language" : "ja", 81 | "text" : "オリンピック大会" 82 | }, 83 | "_ml" : { 84 | "lang_ident" : { 85 | "top_classes" : [ 86 | { 87 | "class_name" : "ja", 88 | "class_probability" : 0.9993823252841599 89 | }, 90 | { 91 | "class_name" : "el", 92 | "class_probability" : 2.6448654791599055E-4 93 | }, 94 | { 95 | "class_name" : "sd", 96 | "class_probability" : 1.4846805271384584E-4 97 | } 98 | ], 99 | "model_id" : "lang_ident_model_1" 100 | } 101 | } 102 | }, 103 | "_ingest" : { 104 | "timestamp" : "2020-01-21T14:41:48.486039Z" 105 | } 106 | } 107 | }, 108 | { 109 | "doc" : { 110 | "_index" : "_index_ko", 111 | "_type" : "_doc", 112 | "_id" : "_id", 113 | "_source" : { 114 | "contents" : { 115 | "language" : "ko", 116 | "text" : "로마는 하루아침에 이루어진 것이 아니다" 117 | }, 118 | "_ml" : { 119 | "lang_ident" : { 120 | "top_classes" : [ 121 | { 122 | "class_name" : "ko", 123 | "class_probability" : 0.9999939196272863 124 | }, 125 | { 126 | "class_name" : "ka", 127 | "class_probability" : 3.0431805047662344E-6 128 | }, 129 | { 130 | "class_name" : "am", 131 | "class_probability" : 1.710514725818281E-6 132 | } 133 | ], 134 | "model_id" : "lang_ident_model_1" 135 | } 136 | } 137 | }, 138 | "_ingest" : { 139 | "timestamp" : "2020-01-21T14:41:48.486041Z" 140 | } 141 | } 142 | }, 143 | { 144 | "doc" : { 145 | "_index" : "_index_zh", 146 | "_type" : "_doc", 147 | "_id" : "_id", 148 | "_source" : { 149 | "contents" : { 150 | "language" : "zh", 151 | "text" : "授人以鱼不如授人以渔" 152 | }, 153 | "_ml" : { 154 | "lang_ident" : { 155 | "top_classes" : [ 156 | { 157 | "class_name" : "zh", 158 | "class_probability" : 0.9999810103320087 159 | }, 160 | { 161 | "class_name" : "ja", 162 | "class_probability" : 1.0390454083183788E-5 163 | }, 164 | { 165 | "class_name" : "ka", 166 | "class_probability" : 2.6302271562335787E-6 167 | } 168 | ], 169 | "model_id" : "lang_ident_model_1" 170 | } 171 | } 172 | }, 173 | "_ingest" : { 174 | "timestamp" : "2020-01-21T14:41:48.486043Z" 175 | } 176 | } 177 | }, 178 | { 179 | "doc" : { 180 | "_index" : "_index", 181 | "_type" : "_doc", 182 | "_id" : "_id", 183 | "_source" : { 184 | "contents" : { 185 | "language" : "fr", 186 | "text" : "Qui court deux lievres a la fois, n’en prend aucun" 187 | }, 188 | "_ml" : { 189 | "lang_ident" : { 190 | "top_classes" : [ 191 | { 192 | "class_name" : "fr", 193 | "class_probability" : 0.9999669852240882 194 | }, 195 | { 196 | "class_name" : "gd", 197 | "class_probability" : 2.3485226102079597E-5 198 | }, 199 | { 200 | "class_name" : "ht", 201 | "class_probability" : 3.536708810360631E-6 202 | } 203 | ], 204 | "model_id" : "lang_ident_model_1" 205 | } 206 | } 207 | }, 208 | "_ingest" : { 209 | "timestamp" : "2020-01-21T14:41:48.486044Z" 210 | } 211 | } 212 | }, 213 | { 214 | "doc" : { 215 | "_index" : "_index", 216 | "_type" : "_doc", 217 | "_id" : "_id", 218 | "_source" : { 219 | "contents" : { 220 | "language" : "la", 221 | "text" : "Lupus non timet canem latrantem" 222 | }, 223 | "_ml" : { 224 | "lang_ident" : { 225 | "top_classes" : [ 226 | { 227 | "class_name" : "la", 228 | "class_probability" : 0.614050940088811 229 | }, 230 | { 231 | "class_name" : "fr", 232 | "class_probability" : 0.32530021315840363 233 | }, 234 | { 235 | "class_name" : "sq", 236 | "class_probability" : 0.03353817054854559 237 | } 238 | ], 239 | "model_id" : "lang_ident_model_1" 240 | } 241 | } 242 | }, 243 | "_ingest" : { 244 | "timestamp" : "2020-01-21T14:41:48.486046Z" 245 | } 246 | } 247 | }, 248 | { 249 | "doc" : { 250 | "_index" : "_index_en", 251 | "_type" : "_doc", 252 | "_id" : "_id", 253 | "_source" : { 254 | "contents" : { 255 | "language" : "en", 256 | "text" : "This is mostly English but has a touch of Latin since we often just say, Carpe diem" 257 | }, 258 | "_ml" : { 259 | "lang_ident" : { 260 | "top_classes" : [ 261 | { 262 | "class_name" : "en", 263 | "class_probability" : 0.9997901768317939 264 | }, 265 | { 266 | "class_name" : "ja", 267 | "class_probability" : 8.756250766054857E-5 268 | }, 269 | { 270 | "class_name" : "fil", 271 | "class_probability" : 1.6980752372837307E-5 272 | } 273 | ], 274 | "model_id" : "lang_ident_model_1" 275 | } 276 | } 277 | }, 278 | "_ingest" : { 279 | "timestamp" : "2020-01-21T14:41:48.48605Z" 280 | } 281 | } 282 | } 283 | ] 284 | } 285 | -------------------------------------------------------------------------------- /examples/simulate-lang-per-index.txt: -------------------------------------------------------------------------------- 1 | # simulate a language per-index and output top 3 language classes for inspection 2 | 3 | POST _ingest/pipeline/_simulate 4 | { 5 | "pipeline": { 6 | "processors": [ 7 | { 8 | "inference": { 9 | "model_id": "lang_ident_model_1", 10 | "inference_config": { 11 | "classification": { 12 | "num_top_classes": 3 13 | } 14 | }, 15 | "field_mappings": { 16 | "contents": "text" 17 | }, 18 | "target_field": "_ml.lang_ident" 19 | } 20 | }, 21 | { 22 | "rename": { 23 | "field": "contents", 24 | "target_field": "contents.text" 25 | } 26 | }, 27 | { 28 | "rename": { 29 | "field": "_ml.lang_ident.predicted_value", 30 | "target_field": "contents.language" 31 | } 32 | }, 33 | { 34 | "set": { 35 | "if": "['de', 'en', 'ja', 'ko', 'zh'].contains(ctx.contents.language)", 36 | "field": "_index", 37 | "value": "{{_index}}_{{contents.language}}", 38 | "override": true 39 | } 40 | } 41 | ] 42 | }, 43 | "docs": [ 44 | { 45 | "_source": { 46 | "contents": "Das leben ist kein Ponyhof" 47 | } 48 | }, 49 | { 50 | "_source": { 51 | "contents": "The rain in Spain stays mainly in the plains" 52 | } 53 | }, 54 | { 55 | "_source": { 56 | "contents": "オリンピック大会" 57 | } 58 | }, 59 | { 60 | "_source": { 61 | "contents": "로마는 하루아침에 이루어진 것이 아니다" 62 | } 63 | }, 64 | { 65 | "_source": { 66 | "contents": "授人以鱼不如授人以渔" 67 | } 68 | }, 69 | { 70 | "_source": { 71 | "contents": "Qui court deux lievres a la fois, n’en prend aucun" 72 | } 73 | }, 74 | { 75 | "_source": { 76 | "contents": "Lupus non timet canem latrantem" 77 | } 78 | }, 79 | { 80 | "_source": { 81 | "contents": "This is mostly English but has a touch of Latin since we often just say, Carpe diem" 82 | } 83 | } 84 | ] 85 | } 86 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # core 2 | pip==19.3.* 3 | 4 | # misc 5 | tqdm==4.38.* 6 | 7 | # search 8 | elasticsearch==7.* 9 | --------------------------------------------------------------------------------