Skip to content

Instantly share code, notes, and snippets.

@serihiro
Last active October 11, 2023 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serihiro/56f8e9e4eecd0874e8083056446964fe to your computer and use it in GitHub Desktop.
Save serihiro/56f8e9e4eecd0874e8083056446964fe to your computer and use it in GitHub Desktop.
Elasticsearch search viewer with Streamlit example
import streamlit as st
from elasticsearch import Elasticsearch
def main():
st.title("Streamlit ES Viewer")
with st.form("my_form", clear_on_submit=False):
keyword = st.text_input("keyword", "Python")
title_weight = st.number_input(
label="title weight", value=1.0, min_value=0.0, max_value=5.0, step=0.1
)
caption_weight = st.number_input(
label="caption weight", value=1.0, min_value=0.0, max_value=5.0, step=0.1
)
submitted = st.form_submit_button("Search")
if submitted:
es = Elasticsearch(hosts="http://localhost:9200")
body = {"query": {"simple_query_string": {}}}
body["query"]["simple_query_string"]["query"] = keyword
body["query"]["simple_query_string"]["fields"] = [
f"title^{title_weight}",
f"itemCaption^{caption_weight}",
]
st.write(body)
result = es.search(index="book", body=body, size=100, explain=True)
result_num = result["hits"]["total"]["value"]
books = result["hits"]["hits"]
st.write(f"Found {result_num} results.")
for book in books:
st.subheader(book["_source"]["title"])
st.image(book["_source"]["largeImageUrl"], width=100)
st.link_button("Link", book["_source"]["itemUrl"])
st.text_area(
key=f"itemCaption_{book['_id']}",
label="商品説明",
value=book["_source"]["itemCaption"],
height=200,
)
st.text(f'score: {book["_score"]}')
st.text(f'author: {book["_source"]["author"]}')
with st.expander("Explain", expanded=False):
st.json(book["_explanation"])
st.divider()
st.write("Done!")
# streamlit run app.py
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment