在今天的文章里,我来详细地介绍如何使用 ELSER 进行文本扩展驱动的语义搜索。
安装
Elasticsearch 及 Kibana
如果你还没有安装好自己的 Elasticsearch 及 Kibana,请参考如下的链接来进行安装:
在安装的时候,我们可以选择 Elastic Stack 8.x 的安装指南来进行安装。在本博文中,我将使用最新的 Elastic Stack 8.10 来进行展示。
在安装 Elasticsearch 的过程中,我们需要记下如下的信息:
部署 ELSER
我们可以参考文章 "Elasticsearch:部署 ELSER - Elastic Learned Sparse EncoderR" 来部署 ELSER。
Python 安装包
在本演示中,我们将使用 Python 来进行展示。我们需要安装访问 Elasticsearch 相应的安装包 elasticsearch:
pip install elasticsearch
我们将使用 Jupyter Notebook 来进行展示。
markdown
1. $ pwd
2. /Users/liuxg/python/elser
3. $ jupyter notebook
准备数据
我们在项目的根目录下,创建如下的一个数据文件: data.json:
data.json
css
1. [2. {3. "title":"Pulp Fiction",4. "runtime":"154",5. "plot":"The lives of two mob hitmen, a boxer, a gangster and his wife, and a pair of diner bandits intertwine in four tales of violence and redemption.",6. "keyScene":"John Travolta is forced to inject adrenaline directly into Uma Thurman's heart after she overdoses on heroin.",7. "genre":"Crime, Drama",8. "released":"1994"9. },10. {11. "title":"The Dark Knight",12. "runtime":"152",13. "plot":"When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, Batman must accept one of the greatest psychological and physical tests of his ability to fight injustice.",14. "keyScene":"Batman angrily responds 'I'm Batman' when asked who he is by Falcone.",15. "genre":"Action, Crime, Drama, Thriller",16. "released":"2008"17. },18. {19. "title":"Fight Club",20. "runtime":"139",21. "plot":"An insomniac office worker and a devil-may-care soapmaker form an underground fight club that evolves into something much, much more.",22. "keyScene":"Brad Pitt explains the rules of Fight Club to Edward Norton. The first rule of Fight Club is: You do not talk about Fight Club. The second rule of Fight Club is: You do not talk about Fight Club.",23. "genre":"Drama",24. "released":"1999"25. },26. {27. "title":"Inception",28. "runtime":"148",29. "plot":"A thief who steals corporate secrets through the use of dream-sharing technology is given the inverse task of planting an idea into thed of a C.E.O.",30. "keyScene":"Leonardo DiCaprio explains the concept of inception to Ellen Page by using a child's spinning top.",31. "genre":"Action, Adventure, Sci-Fi, Thriller",32. "released":"2010"33. },34. {35. "title":"The Matrix",36. "runtime":"136",37. "plot":"A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.",38. "keyScene":"Red pill or blue pill? Morpheus offers Neo a choice between the red pill, which will allow him to learn the truth about the Matrix, or the blue pill, which will return him to his former life.",39. "genre":"Action, Sci-Fi",40. "released":"1999"41. },42. {43. "title":"The Shawshank Redemption",44. "runtime":"142",45. "plot":"Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.",46. "keyScene":"Andy Dufresne escapes from Shawshank prison by crawling through a sewer pipe.",47. "genre":"Drama",48. "released":"1994"49. },50. {51. "title":"Goodfellas",52. "runtime":"146",53. "plot":"The story of Henry Hill and his life in the mob, covering his relationship with his wife Karen Hill and his mob partners Jimmy Conway and Tommy DeVito in the Italian-American crime syndicate.",54. "keyScene":"Joe Pesci's character Tommy DeVito shoots young Spider in the foot for not getting him a drink.",55. "genre":"Biography, Crime, Drama",56. "released":"1990"57. },58. {59. "title":"Se7en",60. "runtime":"127",61. "plot":"Two detectives, a rookie and a veteran, hunt a serial killer who uses the seven deadly sins as his motives.",62. "keyScene":"Brad Pitt's character David Mills shoots John Doe after he reveals that he murdered Mills' wife.",63. "genre":"Crime, Drama, Mystery, Thriller",64. "released":"1995"65. },66. {67. "title":"The Silence of the Lambs",68. "runtime":"118",69. "plot":"A young F.B.I. cadet must receive the help of an incarcerated and manipulative cannibal killer to help catch another serial killer, a madman who skins his victims.",70. "keyScene":"Hannibal Lecter explains to Clarice Starling that he ate a census taker's liver with some fava beans and a nice Chianti.",71. "genre":"Crime, Drama, Thriller",72. "released":"1991"73. },74. {75. "title":"The Godfather",76. "runtime":"175",77. "plot":"An organized crime dynasty's aging patriarch transfers control of his clandestine empire to his reluctant son.",78. "keyScene":"James Caan's character Sonny Corleone is shot to death at a toll booth by a number of machine gun toting enemies.",79. "genre":"Crime, Drama",80. "released":"1972"81. },82. {83. "title":"The Departed",84. "runtime":"151",85. "plot":"An undercover cop and a mole in the police attempt to identify each other while infiltrating an Irish gang in South Boston.",86. "keyScene":"Leonardo DiCaprio's character Billy Costigan is shot to death by Matt Damon's character Colin Sullivan.",87. "genre":"Crime, Drama, Thriller",88. "released":"2006"89. },90. {91. "title":"The Usual Suspects",92. "runtime":"106",93. "plot":"A sole survivor tells of the twisty events leading up to a horrific gun battle on a boat, which began when five criminals met at a seemingly random police lineup.",94. "keyScene":"Kevin Spacey's character Verbal Kint is revealed to be the mastermind behind the crime, when his limp disappears as he walks away from the police station.",95. "genre":"Crime, Mystery, Thriller",96. "released":"1995"97. }98. ]
markdown
1. $ pwd
2. /Users/liuxg/python/elser
3. $ ls
4. Semantic search - ELSER.ipynb data.json
创建应用并进行演示
连接 Elasticsearch
我们可以参考文章 "Elasticsearch:关于在 Python 中使用 Elasticsearch 你需要知道的一切 - 8.x" 在 Python 中连接 Elasticsearch。接下来,我们需要导入我们需要的模块。
javascript
1. from elasticsearch import Elasticsearch, helpers
2. from urllib.request import urlopen
3. import getpass
4. import json
现在我们可以实例化 Python Elasticsearch 客户端。
然后我们创建一个客户端对象来实例化 Elasticsearch 类的实例。
ini
1. ELASTCSEARCH_CERT_PATH = "/Users/liuxg/elastic/elasticsearch-8.10.0/config/certs/http_ca.crt"
3. client = Elasticsearch( ['https://localhost:9200'],
4. basic_auth = ('elastic', 'vXDWYtL*my3vnKY9zCfL'),
5. ca_certs = ELASTCSEARCH_CERT_PATH,
6. verify_certs = True)
🔐 注意:getpass 使我们能够安全地提示用户输入凭据,而无需将其回显到终端或将其存储在内存中。为了方便,我们将不使用 getpass。在代码中我们使用硬编码。你也可以使用 API keys 来进行连接。详细细节,请参考文章 "Elasticsearch:关于在 Python 中使用 Elasticsearch 你需要知道的一切 - 8.x"。
使用 ELSER 索引文档
为了在我们的 Elasticsearch 集群上使用 ELSER,我们需要创建一个包含运行 ELSER 模型的推理处理器的摄取管道。 让我们使用 put_pipeline 方法添加该管道。
ini
1. client.ingest.put_pipeline(
2. id="elser-ingest-pipeline",
3. description="Ingest pipeline for ELSER",
4. processors=[
5. {
6. "inference": {
7. "model_id": ".elser_model_1",
8. "target_field": "ml",
9. "field_map": {
10. "plot": "text_field"
11. },
12. "inference_config": {
13. "text_expansion": {
14. "results_field": "tokens"
15. }
16. }
17. }
18. }
19. ]
20. )
让我们记下该 API 调用中的一些重要参数:
- inference:使用机器学习模型执行推理的处理器。
- model_id:指定要使用的机器学习模型的 ID。 在此示例中,模型 ID 设置为 .elser_model_1。
- target_field:定义存储推理结果的字段。 这里设置为 ml。
- text_expansion:为推理过程配置文本扩展选项。 在此示例中,推理结果将存储在名为 "tokens" 的字段中。
使用映射创建索引
要在索引时使用 ELSER 模型,我们需要创建支持 text_expansion 查询的索引映射。 映射必须包含 rank_features 类型的字段才能使用我们感兴趣的特征向量。 该字段包含 ELSER 模型根据输入文本创建的 token 权重对。
让我们使用我们需要的映射创建一个名为 elser-example-movies 的索引。
lua
1. client.indices.create(
2. index="elser-example-movies",
3. settings={
4. "index": {
5. "number_of_shards": 1,
6. "number_of_replicas": 1,
7. "default_pipeline": "elser-ingest-pipeline"
8. }
9. },
10. mappings={
11. "properties": {
12. "plot": {
13. "type": "text",
14. "fields": {
15. "keyword": {
16. "type": "keyword",
17. "ignore_above": 256
18. }
19. }
20. },
21. "ml.tokens": {
22. "type": "rank_features"
23. },
24. }
25. }
26. )
在运行完上面的代码后,我们可以在 Kibana 里进行查看:
bash
GET elser-example-movies/_mapping
从上面的输出中,我们可以看到 elser-example-movies 索引已经被成功地创建。
摄入文档
让我们插入 12 部电影的示例数据集。
python
1. # Load data into a JSON object
2. with open('data.json') as f:
3. data_json = json.load(f)
5. print(data_json)
7. # Prepare the documents to be indexed
8. documents = []
9. for doc in data_json:
10. documents.append({
11. "_index": INDEX_NAME,
12. "_source": doc,
13. })
15. # Use helpers.bulk to index
16. helpers.bulk(client, documents)
18. print("Done indexing documents into `search-movies` index!")
我们可以到 Kibana 里进行查看:
bash
GET elser-example-movies/_search
检查新文档以确认它现在有一个 "ml": {"tokens":...} 字段,其中包含新的附加术语列表。 这些术语是你针对 ELSER 推理的字段的文本扩展。 ELSER 实质上创建了一个扩展术语树,以提高文档的语义可搜索性。 我们将能够使用 text_expansion 查询来搜索这些文档。
但首先让我们从简单的关键字搜索开始,看看 ELSER 如何提供开箱即用的语义相关结果。
使用 ELSER 查询文档
让我们使用 ELSER 测试语义搜索。
ini
1. response = client.search(
2. index='elser-example-movies',
3. size=3,
4. query={
5. "text_expansion": {
6. "ml.tokens": {
7. "model_id":".elser_model_1",
8. "model_text":"child toy"
9. }
10. }
11. }
12. )
14. for hit in response['hits']['hits']:
15. doc_id = hit['_id']
16. score = hit['_score']
17. title = hit['_source']['title']
18. plot = hit['_source']['plot']
19. print(f"Score: {score}\nTitle: {title}\nPlot: {plot}\n")