|
| 1 | +# Licensed to Elasticsearch B.V. under one or more contributor |
| 2 | +# license agreements. See the NOTICE file distributed with |
| 3 | +# this work for additional information regarding copyright |
| 4 | +# ownership. Elasticsearch B.V. licenses this file to you under |
| 5 | +# the Apache License, Version 2.0 (the "License"); you may |
| 6 | +# not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | + |
| 18 | + |
| 19 | +""" |
| 20 | +# Semantic Text example |
| 21 | +
|
| 22 | +Requirements: |
| 23 | +
|
| 24 | +$ pip install "elasticsearch-dsl[async]" tqdm |
| 25 | +
|
| 26 | +Before running this example, an ELSER inference endpoint must be created in the |
| 27 | +Elasticsearch cluster. This can be done manually from Kibana, or with the |
| 28 | +following curl command from a terminal: |
| 29 | +
|
| 30 | +curl -X PUT \ |
| 31 | + "$ELASTICSEARCH_URL/_inference/sparse_embedding/my-elser-endpoint" \ |
| 32 | + -H "Content-Type: application/json" \ |
| 33 | + -d '{"service":"elser","service_settings":{"num_allocations":1,"num_threads":1}}' |
| 34 | +
|
| 35 | +To run the example: |
| 36 | +
|
| 37 | +$ python semantic_text.py "text to search" |
| 38 | +
|
| 39 | +The index will be created automatically if it does not exist. Add |
| 40 | +`--recreate-index` to the command to regenerate it. |
| 41 | +
|
| 42 | +The example dataset includes a selection of workplace documents. The |
| 43 | +following are good example queries to try out with this dataset: |
| 44 | +
|
| 45 | +$ python semantic_text.py "work from home" |
| 46 | +$ python semantic_text.py "vacation time" |
| 47 | +$ python semantic_text.py "can I bring a bird to work?" |
| 48 | +
|
| 49 | +When the index is created, the inference service will split the documents into |
| 50 | +short passages, and for each passage a sparse embedding will be generated using |
| 51 | +Elastic's ELSER v2 model. |
| 52 | +""" |
| 53 | + |
| 54 | +import argparse |
| 55 | +import asyncio |
| 56 | +import json |
| 57 | +import os |
| 58 | +from datetime import datetime |
| 59 | +from typing import Any, Optional |
| 60 | +from urllib.request import urlopen |
| 61 | + |
| 62 | +from tqdm import tqdm |
| 63 | + |
| 64 | +import elasticsearch_dsl as dsl |
| 65 | + |
| 66 | +DATASET_URL = "https://raw.githubusercontent.com/elastic/elasticsearch-labs/main/datasets/workplace-documents.json" |
| 67 | + |
| 68 | + |
| 69 | +class WorkplaceDoc(dsl.AsyncDocument): |
| 70 | + class Index: |
| 71 | + name = "workplace_documents_semantic" |
| 72 | + |
| 73 | + name: str |
| 74 | + summary: str |
| 75 | + content: Any = dsl.mapped_field( |
| 76 | + dsl.field.SemanticText(inference_id="my-elser-endpoint") |
| 77 | + ) |
| 78 | + created: datetime |
| 79 | + updated: Optional[datetime] |
| 80 | + url: str = dsl.mapped_field(dsl.Keyword()) |
| 81 | + category: str = dsl.mapped_field(dsl.Keyword()) |
| 82 | + |
| 83 | + |
| 84 | +async def create() -> None: |
| 85 | + |
| 86 | + # create the index |
| 87 | + await WorkplaceDoc._index.delete(ignore_unavailable=True) |
| 88 | + await WorkplaceDoc.init() |
| 89 | + |
| 90 | + # download the data |
| 91 | + dataset = json.loads(urlopen(DATASET_URL).read()) |
| 92 | + |
| 93 | + # import the dataset |
| 94 | + for data in tqdm(dataset, desc="Indexing documents..."): |
| 95 | + doc = WorkplaceDoc( |
| 96 | + name=data["name"], |
| 97 | + summary=data["summary"], |
| 98 | + content=data["content"], |
| 99 | + created=data.get("created_on"), |
| 100 | + updated=data.get("updated_at"), |
| 101 | + url=data["url"], |
| 102 | + category=data["category"], |
| 103 | + ) |
| 104 | + await doc.save() |
| 105 | + |
| 106 | + # refresh the index |
| 107 | + await WorkplaceDoc._index.refresh() |
| 108 | + |
| 109 | + |
| 110 | +async def search(query: str) -> dsl.AsyncSearch[WorkplaceDoc]: |
| 111 | + search = WorkplaceDoc.search() |
| 112 | + search = search[:5] |
| 113 | + return search.query(dsl.query.Semantic(field=WorkplaceDoc.content, query=query)) |
| 114 | + |
| 115 | + |
| 116 | +def parse_args() -> argparse.Namespace: |
| 117 | + parser = argparse.ArgumentParser(description="Vector database with Elasticsearch") |
| 118 | + parser.add_argument( |
| 119 | + "--recreate-index", action="store_true", help="Recreate and populate the index" |
| 120 | + ) |
| 121 | + parser.add_argument("query", action="store", help="The search query") |
| 122 | + return parser.parse_args() |
| 123 | + |
| 124 | + |
| 125 | +async def main() -> None: |
| 126 | + args = parse_args() |
| 127 | + |
| 128 | + # initiate the default connection to elasticsearch |
| 129 | + dsl.async_connections.create_connection(hosts=[os.environ["ELASTICSEARCH_URL"]]) |
| 130 | + |
| 131 | + if args.recreate_index or not await WorkplaceDoc._index.exists(): |
| 132 | + await create() |
| 133 | + |
| 134 | + results = await search(args.query) |
| 135 | + |
| 136 | + async for hit in results: |
| 137 | + print( |
| 138 | + f"Document: {hit.name} [Category: {hit.category}] [Score: {hit.meta.score}]" |
| 139 | + ) |
| 140 | + print(f"Content: {hit.content.text}") |
| 141 | + print("--------------------\n") |
| 142 | + |
| 143 | + # close the connection |
| 144 | + await dsl.async_connections.get_connection().close() |
| 145 | + |
| 146 | + |
| 147 | +if __name__ == "__main__": |
| 148 | + asyncio.run(main()) |
0 commit comments