elasticsearch客户端简易封装

# es get _cat
# host=127.0.0.1:9200 es post _sql -d '{ "query": "select * from data"}'
# export ES_HOST=127.0.0.1:9200
# es post _sql -d '{ "query": "select * from data"}'
# es post _sql 'select * from data'
es() {
    local method=$1
    method=$(echo "$method" | awk '{ print toupper($0) }')

    local url=$2
    [ "${url:0:1}" = / ] || url="/$url"
    echo "$url" | grep "?" >/dev/null && url="$url&pretty"

    local host
    [ -z "$host" ] && host=$ES_HOST
    [ -z "$host" ] && host=127.0.0.1:9200

    shift 2

    if [ ${url:0:5} = /_sql ]; then
        local body=$(jq -n --arg sql "$@" '{"query": $sql}')
        curl -X "$method" "$host$url" \
            -H 'Content-Type: application/json' \
            -d "$body"
    else
        curl -X "$method" "$host$url" \
            -H 'Content-Type: application/json' \
            "$@"
    fi
}

关闭