Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

KeyError: 'metadata' when elasticsearch index does not have 'metadata' field, and no "fields" is passed to _search() #7

Closed
masihsultani opened this issue Apr 5, 2024 · 1 comment

Comments

@masihsultani
Copy link
Contributor

masihsultani commented Apr 5, 2024

https://github.com/langchain-ai/langchain-elastic/blob/89fafbe1dc59caa2f3dab81db2143fe20b4b7738/libs/elasticsearch/langchain_elasticsearch/vectorstores.py#L889C1-L913C14

When no fields is passed and elasticsearch index mapping does not have "metadata" field, runs in to KeyError: 'metadata' on line 892 metadata=hit["_source"]["metadata"]. This should be changed to metadata=hit["_source"].get("metadata",{}) or alternatively move this if statement lines(904-905) outside and before if statement 900. Should be:

for hit in response["hits"]["hits"]:
            for field in fields:
                if "metadata" not in hit["_source"]:
                        hit["_source"]["metadata"] = {}
                if field in hit["_source"] and field not in [
                    "metadata",
                    self.query_field,
                ]:
                    
                    hit["_source"]["metadata"][field] = hit["_source"][field]

            docs_and_scores.append(
                (
                    doc_builder(hit),
                    hit["_score"],
                )
            )
maxjakob added a commit that referenced this issue Apr 22, 2024
* fixed KeyError:'metadata' when metadata field isn't present in elastic mapping. Moved if statement earlier and outside of other if statement to catch this case, also used .get() for dictionary with default value if key is not present

* Update libs/elasticsearch/langchain_elasticsearch/vectorstores.py

* Update libs/elasticsearch/langchain_elasticsearch/vectorstores.py

---------

Co-authored-by: Max Jakob <[email protected]>
@maxjakob
Copy link
Collaborator

Closed by #8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants