Elasticsearch更新和刷新API

问题描述 投票:0回答:2

我正在将弹性搜索与我的 Nest 应用程序集成。在下面提出我的工作流程和问题。

流量:

  • 前端更新一个实体,所以后端更新主存储MYSQL和缓存存储elasticsearch。
  • 前端立即发起 get 请求来获取更新后的实体,因此后端从 elastic-search 中获取实体并向前端发送响应。
  • 现在的问题是有时弹性搜索由于索引未刷新而给出未更新的数据。

解决方案:

  • 我们可以在更新 API 中使用
    refresh:'wait-for'
    配置。
  • 我们可以触发刷新API来刷新索引
    • 问题是,更新API后,如果我们不等待结果就触发刷新API。同时,如果前端请求数据会发生什么,弹性搜索将等待刷新索引操作完成还是会提供旧数据?
node.js elasticsearch nestjs
2个回答
0
投票

正如您所知,Elasticsearch 提供近实时搜索,如果您正在进行搜索调用,一旦文档被索引到 Elasticsearch,除非索引上发生

refresh
,否则该文档将不可用。

现在,正如您所提到的,您可以通过在索引/更新操作中使用

wait_for
来解决问题,唯一的缺点是它会占用大量资源,如果您在大型索引上频繁执行此操作,可能会导致严重的性能问题你的集群。

您的第二个选项将不起作用,因为您仍然可以在刷新完成之前从 FE 查询 Elasticsearch,并且您将获得过时的数据。


0
投票

我遇到了类似的问题,需要输入至少 1 秒的等待时间。 我尝试了0.5秒,无法正确检索数据。 这对我有帮助:

# Function to retrieve the balance for a specific patient
def get_patient_balance(es_client, STRUCTURED_INDEX_NAME, patient_name):
    query = {
        "query": {
            "match": {
                "Patient Name": patient_name
            }
        }
    }
    response = es_client.search(index=STRUCTURED_INDEX_NAME, body=query)
    if response['hits']['total']['value'] > 0:
        return response['hits']['hits'][0]['_source']['Balance Remaining']
    else:
        return None

然后输入:

# Wait for a short period to ensure data is indexed
time.sleep(1)


# Now run the query
patient_3_balance = get_patient_balance(es_client, STRUCTURED_INDEX_NAME, 'Patient_3')
if patient_3_balance is not None:
    print(f"Patient_3 Balance Remaining: {patient_3_balance:.2f}")
else:
    print("Patient_3 Balance Remaining: Data not found")

patient_39_balance = get_patient_balance(es_client, STRUCTURED_INDEX_NAME, 'Patient_39')
if patient_39_balance is not None:
    print(f"Patient_39 Balance Remaining: {patient_39_balance:.2f}")
else:
    print("Patient_39 Balance Remaining: Data not found")

if patient_3_balance is not None and patient_39_balance is not None:
    step_1 = patient_3_balance
    print(f"Step 1: {step_1:.2f}")

    step_2 = step_1 + patient_39_balance
    print(f"Step 2: {step_1:.2f} + {patient_39_balance:.2f} = {step_2:.2f}")

    combined_balance = step_2
    print(f"The combined remaining balance of Patient_3 and Patient_39 is: {combined_balance:.2f}")
else:
    print("Unable to calculate combined balance due to missing data")
Patient_39 Balance Remaining: 3018.84
Step 1: 37.34
Step 2: 37.34 + 3018.84 = 3056.18
The combined remaining balance of Patient_3 and Patient_39 is: 3056.18

之前它说“找不到数据”...

© www.soinside.com 2019 - 2024. All rights reserved.