您的位置:首頁(yè) > 軟件教程 > 教程 > 連接Elasticsearch服務(wù)器的Python代碼示例

連接Elasticsearch服務(wù)器的Python代碼示例

來(lái)源:好特整理 | 時(shí)間:2024-10-25 09:46:34 | 閱讀:178 |  標(biāo)簽: a T last El S C AR 服務(wù) 代碼 服務(wù)器 EA cs Python   | 分享到:

連接Elasticsearch(ES)服務(wù)器是進(jìn)行數(shù)據(jù)搜索和分析的常用操作。Elasticsearch是一個(gè)基于Lucene的搜索引擎,提供了RESTful API來(lái)進(jìn)行索引、搜索和管理數(shù)據(jù)。

連接Elasticsearch(ES)服務(wù)器是進(jìn)行數(shù)據(jù)搜索和分析的常用操作。Elasticsearch是一個(gè)基于Lucene的搜索引擎,提供了RESTful API來(lái)進(jìn)行索引、搜索和管理數(shù)據(jù)。

以下是一個(gè)詳細(xì)的Python代碼示例,展示如何連接到Elasticsearch服務(wù)器并執(zhí)行一些基本操作。這個(gè)示例使用了官方的 elasticsearch-py 客戶端庫(kù)。

1. 安裝Elasticsearch客戶端庫(kù)

首先,你需要安裝 elasticsearch 庫(kù)。如果你還沒(méi)有安裝,可以使用pip進(jìn)行安裝:

bash
pip install elasticsearch

2. 連接到Elasticsearch服務(wù)器

以下是一個(gè)完整的Python腳本,展示了如何連接到Elasticsearch服務(wù)器,創(chuàng)建索引,添加文檔,并進(jìn)行搜索。

from elasticsearch import Elasticsearch, helpers  
  
# 配置Elasticsearch連接  
es = Elasticsearch(  
    ['http://localhost:9200'],  # Elasticsearch服務(wù)器地址和端口  
    http_auth=('username', 'password'),  # 如果需要認(rèn)證,填寫用戶名和密碼  
    use_ssl=False,  # 如果使用HTTPS,設(shè)置為True  
    verify_certs=False  # 如果使用HTTPS且自簽名證書,設(shè)置為False  
)  
  
# 檢查連接是否成功  
if es.ping():  
    print("Successfully connected to Elasticsearch!")  
else:  
    print("Could not connect to Elasticsearch")  
    exit()  
  
# 創(chuàng)建索引  
index_name = 'my_index'  
if not es.indices.exists(index=index_name):  
    # 定義索引的映射(Schema)  
    mappings = {  
        'properties': {  
            'title': {'type': 'text'},  
            'content': {'type': 'text'},  
            'author': {'type': 'keyword'}  
        }  
    }  
    # 創(chuàng)建索引  
    es.indices.create(index=index_name, body={'mappings': mappings})  
    print(f"Index '{index_name}' created successfully.")  
else:  
    print(f"Index '{index_name}' already exists.")  
  
# 添加文檔  
documents = [  
    {"_id": 1, "title": "Elasticsearch Basics", "content": "Learn the basics of Elasticsearch.", "author": "John Doe"},  
    {"_id": 2, "title": "Advanced Elasticsearch", "content": "Go deeper into Elasticsearch features.", "author": "Jane Smith"},  
    {"_id": 3, "title": "Elasticsearch Performance", "content": "Optimize Elasticsearch for performance.", "author": "Alice Johnson"}  
]  
  
# 使用bulk API批量添加文檔  
actions = [  
    {  
        "_index": index_name,  
        "_id": doc['_id'],  
        "_source": doc  
    }  
    for doc in documents  
]  
  
helpers.bulk(es, actions)  
print("Documents added successfully.")  
  
# 搜索文檔  
search_body = {  
    "query": {  
        "match": {  
            "content": "Elasticsearch"  
        }  
    }  
}  
  
response = es.search(index=index_name, body=search_body)  
print("Search results:")  
for hit in response['hits']['hits']:  
    print(hit['_source'])  
  
# 清理(可選):刪除索引  
# es.indices.delete(index=index_name)  
# print(f"Index '{index_name}' deleted successfully.")

3. 代碼解釋

  1. 連接配置:
    • Elasticsearch(['http://localhost:9200']) :連接到運(yùn)行在本地主機(jī)上的Elasticsearch服務(wù)器,默認(rèn)端口為9200。
    • http_auth=('username', 'password') :如果Elasticsearch服務(wù)器需要認(rèn)證,填寫用戶名和密碼。
    • use_ssl verify_certs :如果連接使用HTTPS,可以啟用這些選項(xiàng)。
  2. 檢查連接:
    • 使用 es.ping() 方法檢查連接是否成功。
  3. 創(chuàng)建索引:
    • 使用 es.indices.exists(index=index_name) 檢查索引是否存在。
    • 使用 es.indices.create(index=index_name, body={'mappings': mappings}) 創(chuàng)建索引,并定義文檔的映射。
  4. 添加文檔:
    • 使用 helpers.bulk(es, actions) 批量添加文檔到索引中。
  5. 搜索文檔:
    • 使用 es.search(index=index_name, body=search_body) 進(jìn)行搜索,并打印搜索結(jié)果。
  6. 清理(可選):
    • 使用 es.indices.delete(index=index_name) 刪除索引。

4. 注意事項(xiàng)

  • 服務(wù)器地址 :確保Elasticsearch服務(wù)器正在運(yùn)行,并且地址和端口配置正確。
  • 認(rèn)證 :如果Elasticsearch服務(wù)器需要認(rèn)證,確保提供正確的用戶名和密碼。
  • SSL :如果連接使用HTTPS,請(qǐng)正確配置 use_ssl verify_certs 選項(xiàng)。

小編推薦閱讀

好特網(wǎng)發(fā)布此文僅為傳遞信息,不代表好特網(wǎng)認(rèn)同期限觀點(diǎn)或證實(shí)其描述。

a 1.0
a 1.0
類型:休閑益智  運(yùn)營(yíng)狀態(tài):正式運(yùn)營(yíng)  語(yǔ)言:中文   

游戲攻略

游戲禮包

游戲視頻

游戲下載

游戲活動(dòng)

《alittletotheleft》官網(wǎng)正版是一款備受歡迎的休閑益智整理游戲。玩家的任務(wù)是對(duì)日常生活中的各種雜亂物

相關(guān)視頻攻略

更多

掃二維碼進(jìn)入好特網(wǎng)手機(jī)版本!

掃二維碼進(jìn)入好特網(wǎng)微信公眾號(hào)!

本站所有軟件,都由網(wǎng)友上傳,如有侵犯你的版權(quán),請(qǐng)發(fā)郵件[email protected]

湘ICP備2022002427號(hào)-10 湘公網(wǎng)安備:43070202000427號(hào)© 2013~2024 haote.com 好特網(wǎng)