How to create a search field for the app

Summary

Hello, I want to create a search field in the sidebar of my QnA page. So I have a QnA page which have a set of questions for each answer and I have also added paging which we can set how many QnA we want to see in each page. Now the problem comes when I made many QnA its too hard to find a particular question. I want a search field in the sidebar using which whatever question we enter in it, we automatically get to that page and scroll to that question. How can I achieve this.

Code snippet:

import streamlit as st
import time
from math import ceil

st.set_page_config(layout="wide")
# with open("designing.css") as source_des:
#     st.markdown(f"<style>{source_des.read()}</style>",unsafe_allow_html=True)
st.title('Knowledge Base')

if "num_questions" not in st.session_state:
    st.session_state.num_questions = 0

if "question" not in st.session_state:
    st.session_state.question = []

if "answer" not in st.session_state:
    st.session_state.answer = []

if "qindex" not in st.session_state:
    st.session_state.qindex = []

if "refresh" not in st.session_state:
    st.session_state.refresh = 0

# for k, v in st.session_state.items():
#     st.session_state[k] = v

def delete_qna(i):
    print(f'popping index {i}')
    st.session_state['qindex'].pop(i)
    st.session_state['answer'].pop(i)
    st.session_state['question'].pop(i)
    st.session_state["num_questions"] -= 1
    print(st.session_state)

def delete_question(i,j):
    print(f'popping index {i}')
    st.session_state.qindex[i] -= 1
    st.session_state['question'][i].pop(j)
    print(st.session_state)

head1, head2 = st.columns([3,3])
if head1.button('Load'):
    head1.write('File Loaded')
else:
    pass

if head2.button('Save'):
    head2.write('File Saved')
else:
    pass

with st.sidebar:
    if st.button("Add QnA"):
        st.session_state["num_questions"] += 1
    else:
        pass

    page_columns = st.columns(2)
    a_per_page = page_columns[1].slider('Answers per Page',1, 30,15, key='a_per_page')
    last_page = ceil(st.session_state.num_questions/a_per_page)
    page = page_columns[0].selectbox('page',range(1,last_page+1), key='page')

    # Compare current page selection to first and last page number

    if page == 1:
        first = True
    else:
        first = False
    if page == last_page:
        last = True
    else:
        last = False

answer_index = st.session_state.num_questions

# Getting the range of current page

if answer_index > 0:
    first = (page-1)*a_per_page
    next = min(first + a_per_page, answer_index)

# Rendering QnA on current page

    for i in range(first,next):
    
        if i >= len(st.session_state.question):
            st.session_state.question.append([])
        
        if i >= len(st.session_state.answer):
            st.session_state.answer.append('')
        
        if i >= len(st.session_state.qindex):
            st.session_state.qindex.append(0)

        con = st.container()
        if con.button("Add Questions", key = f"{i}.Add Questions"):
            st.session_state.qindex[i] += 1
        else:
            pass
        # if con.button(f"{i}.Delete Questions"):
        #     st.session_state.qindex[i] -= 1
        # else:
        #     pass
        
        col1, col2 = con.columns([5, 5])
        col1.text("Questions")
        col2.text("Answer")
        for j in range(st.session_state.qindex[i]):
            if j >= len(st.session_state.question[i]):
                st.session_state.question[i].append('')
            
            st.session_state.question[i][j] = col1.text_input(
                f"question_{i}_{j}",
                label_visibility="collapsed",
                value = st.session_state.question[i][j]
            )
            col1.button("❌", key = f"{i}.{j}.❌", on_click=delete_question, args=[i,j])

        with col2:
            st.session_state.answer[i] = st.text_area(f"ans_{i}", label_visibility="collapsed", value=st.session_state.answer[i])
        con.button("Delete QnA", key = f"{i}.Delete QnA", on_click=delete_qna, args=[i])
        con.text("-------------------------------------------------------------------------------------------------------------------------")
    
if st.session_state.refresh==1:
    st.session_state.refresh = 0
    time.sleep(3)
    st.experimental_rerun()
# print(st.session_state)

This is the structure of my code.
Thank you

@mathcatsand or anyone can you please help?

Save your QnA in a database, json file, sqlite, etc. If there is item in the search field, query it on your database. Save the query results. Build a template page or something and input those query results on the template page and show the template page to the user.

1 Like

One simple way to approach this is to filter the Q & A based on the text input. Here is a simple example using st_keyup (though you could do the same thing with st.text_input) – you can see the code by clicking β€œShow code”

2 Likes