cedricvlt / streamlit-condition-tree

A Streamlit component to build a condition tree
MIT License
68 stars 8 forks source link
conditions elasticsearch filters jsonlogic mongodb spel sql streamlit-component

Based on react-awesome-query-builder

Check out live demo !

This component allows users to build complex condition trees that can be used to filter a dataframe or build a query.

preview

Install

pip install streamlit-condition-tree

Features

Basic usage

Filter a dataframe

import pandas as pd
from streamlit_condition_tree import condition_tree, config_from_dataframe

# Initial dataframe
df = pd.DataFrame({
    'First Name': ['Georges', 'Alfred'],
    'Age': [45, 98],
    'Favorite Color': ['Green', 'Red'],
    'Like Tomatoes': [True, False]
})

# Basic field configuration from dataframe
config = config_from_dataframe(df)

# Condition tree
query_string = condition_tree(
  config,
  always_show_buttons=True,
  placeholder="Empty condition tree"
)

# Filtered dataframe
df = df.query(query_string)

Build a query

import streamlit as st
from streamlit_condition_tree import condition_tree

# Build a custom configuration
config = {
    'fields': {
        'name': {
            'label': 'Name',
            'type': 'text',
        },
        'age': {
            'label': 'Age',
            'type': 'number',
            'fieldSettings': {
                'min': 0
            },
        },
        'like_tomatoes': {
            'label': 'Likes tomatoes',
            'type': 'boolean',
        }
    }
}

# Condition tree
return_val = condition_tree(
    config,
    return_type='sql'
)

# Generated SQL
st.write(return_val)

API

Parameters

def condition_tree(
    config: dict,
    return_type: str [Optional],
    tree: dict [Optional],
    min_height: int [Optional],
    placeholder: str [Optional],
    always_show_buttons: bool [Optional],
    key: str [Optional]
)

A basic configuration can be built from a DataFrame with config_from_dataframe.
For a more advanced configuration, see the component doc and demo. Custom javascript functions must be wrapped into the JsCode class (see Advanced config)

Export & import a condition tree

When a key is defined for the component, the condition tree generated is accessible through st.session_state[key] as a dictionary.
It can be loaded as an input tree through the tree parameter.