お金をかけずにサーバーの勉強をしよう

OpenSearchのインデックスに Pythonでデータを突っ込む

2023年7月13日

メニューへ戻る

こんにちは。

OpenSearchインストール」でデータベースが動くようにし、
OpenSearch Dashboardsインストール」で、ダッシュボードも使えるようになり、
OpenSearchのユーザー追加」で、一般ユーザーを登録することができました。

ここではやっとデータ投入をやっていこうと思います。
私のクライアントPCの Lubuntu 22.04.2でやっています。


何か全文検索したそうな良いデータは無いものか?と考えた末、このホームページの HTMLファイルの内容が使えそうなので、それをやってみようと思います。

[homepage_index] という名前のインデックスにして、構成はシンプルに、

{ ファイル名(filename) : そのファイルの内容(htmltext) }

とします。

まずは、インデックスの作成およびフィールドのデータ型の特定をします。
この作業は「マッピング」って言いますね。

subro@Lubuntu2204:~$ curl -s -u 'subro:パスワード' -k -X PUT https://UbuntuServer2204-1:9200/homepage_index -H 'Content-Type: application/json' -d '
{
  "mappings": {
    "properties": {
      "filename": { "type": "text" },
      "htmltext": { "type": "text" }
    }
  }
}
'  ← ここまでがコマンドです

{"acknowledged":true,"shards_acknowledged":true,"index":"homepage_index"}  ← コマンドの実行結果です

インデックスの枠(データの容れもの)ができて、マッピングもできました。

マッピングはしなくても良いのですが、ちゃんとデータ型を定義しておいたほうが、検索精度とスピートがアップしたはずです。


ここからデータ投入になりますが、Pythonを使います。

OpenSearchは Pythonのクライアントを出していますね。
opensearch-project/opensearch-py

opensearch-pyモジュールをダウンロード(インストール)します。

subro@Lubuntu2204:~$ python3 -m pip install opensearch-py
Defaulting to user installation because normal site-packages is not writeable
Collecting opensearch-py
  Downloading opensearch_py-2.2.0-py2.py3-none-any.whl (291 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 291.0/291.0 KB 7.1 MB/s eta 0:00:00
Requirement already satisfied: requests<3.0.0,>=2.4.0 in /usr/lib/python3/dist-packages (from opensearch-py) (2.25.1)
Requirement already satisfied: python-dateutil in /usr/lib/python3/dist-packages (from opensearch-py) (2.8.1)
Collecting certifi>=2022.12.07
  Downloading certifi-2023.5.7-py3-none-any.whl (156 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 157.0/157.0 KB 11.3 MB/s eta 0:00:00
Requirement already satisfied: urllib3<2,>=1.21.1 in ./.local/lib/python3.10/site-packages (from opensearch-py) (1.26.13)
Requirement already satisfied: six in /usr/lib/python3/dist-packages (from opensearch-py) (1.16.0)
Installing collected packages: certifi, opensearch-py
  Attempting uninstall: certifi
    Found existing installation: certifi 2022.9.24
    Uninstalling certifi-2022.9.24:
      Successfully uninstalled certifi-2022.9.24
Successfully installed certifi-2023.5.7 opensearch-py-2.2.0

インストールできました。

コレを使って本家ドキュメントにあるコードをパクりながら以下のようなものを作りました。
単に1ファイル毎に APIを叩いてデータを挿入しているだけです。

[textjson.py]

import os
import glob
from opensearchpy import OpenSearch
from pathlib import Path
import json

client = OpenSearch(
    hosts = [{'host': 'UbuntuServer2204-1', 'port': 9200}],
    http_compress = True,
    http_auth = ('subro', 'パスワード'),
    use_ssl = True,
    verify_certs = False
)

files = glob.glob(os.environ['HOME'] + "/work/homepage/*.html")

for file in files:

    content = Path(file).read_text()
    file_name = os.path.basename(file)

    document = { 'filename': file_name , 'htmltext': content }

    response = client.index(
        index = 'homepage_index',
        body = document,
        refresh = True
    )

    print (response)

実行します。

subro@Lubuntu2204:~$ python3 textjson.py

〜〜〜 省略 〜〜〜

/home/subro/.local/lib/python3.10/site-packages/urllib3/connectionpool.py:1045: InsecureRequestWarning: Unverified HTTPS request is being made to host 'ubuntuserver2204-1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
{'_index': 'homepage_index', '_id': 'QjFBTokB6BNJJMGnDKMW', '_version': 1, 'result': 'created', 'forced_refresh': True, '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 210, '_primary_term': 1}
/home/subro/.local/lib/python3.10/site-packages/urllib3/connectionpool.py:1045: InsecureRequestWarning: Unverified HTTPS request is being made to host 'ubuntuserver2204-1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(
{'_index': 'homepage_index', '_id': 'QzFBTokB6BNJJMGnDKMr', '_version': 1, 'result': 'created', 'forced_refresh': True, '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 211, '_primary_term': 1}

データは入っていますね。
オレオレ証明書なんで証明書の検証をしないようにしているせいかワーニングが出ていますが、それはとりあえず無視で。


OpenSearch Dashboardsにログインしましょう。
ウチの環境では [http://UbuntuServer2204-1:5601] です。

インデックスを作った [subro]ユーザーでログインします。
Log inを押します。
OpneSearch Dashboards での検索結果 1

ハンバーガーメニューのを押すと出てくるメニューから、
[OpenSerch Dashboards] → [Discover] と選択します。
OpneSearch Dashboards での検索結果 2

Create index patternを押します。
OpneSearch Dashboards での検索結果 3

インデックスの名前に何の条件も就けてなかったので、[subro]ユーザーが見ることのできるインデックスが全てリストアップされます。
[homepage_index]インデックスがありますね。
このインデックス名を上の [index pattern name]に書きます。
OpneSearch Dashboards での検索結果 4

Next stepを押します。
OpneSearch Dashboards での検索結果 5

Create index patternを押します。
OpneSearch Dashboards での検索結果 6

インデックスパターンができました。
[filename] と [htmltext] が検索可能になっています。
OpneSearch Dashboards での検索結果 7

改めてハンバーガーメニューのを押すと出てくるメニューから、
[OpenSerch Dashboards] → [Discover] と選択します。
OpneSearch Dashboards での検索結果 2

何やら出てきました。
検索条件を付けていないので、全212件が表示されています。
OpneSearch Dashboards での検索結果 8

表示する要素を [filename] と [htmltext] に限定します。
左側の赤枠の部分にマウスを持っていくとが出ますから、それを押します。
OpneSearch Dashboards での検索結果 9

このようになりました。
OpneSearch Dashboards での検索結果 10

ここに検索文字列を入れて、Enterを押します。
OpneSearch Dashboards での検索結果 11

そうすると「Windows」って文言が入っているものが抽出されているはずなんで、1番上に出てきた行の > をクリックして中身を見ます。
こういうのを「ドリルダウン」てよく言いますね。
OpneSearch Dashboards での検索結果 12

更に [htmltext]の > をクリックして中身を見ます。
OpneSearch Dashboards での検索結果 13

このように展開されて、「Windows」という文言があった箇所が黄色くなっています。
OpneSearch Dashboards での検索結果 14
こんな感じに使うことができます。


さて、試しに日本語の「お金をかけずに」で検索してみます。

何故か「を」も検索対象になってしまっています。
OpneSearch Dashboards での検索結果 15

これは検索が日本語に対応していないことが原因と思いますので、「OpenSearchで日本語の検索をする」に書いています。