Skip to content

what's the best practice to get a single value from arrow array? #3497

@heyGrant

Description

@heyGrant

code first as below:
(you can skip and see the bottom codes about how to get a single value, it's my way, but I don't like it.)

use std::sync::Arc;
use datafusion::arrow::datatypes::{
  DataType,
  Field,
  Schema};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::arrow::array::StringBuilder;
use datafusion::arrow::array::StringArray;
 
#[tokio::main]
async fn main(){
  // create an arrow array first:
    let mut sbuilder = StringBuilder::new(100);
    sbuilder.append_value("a").unwrap();
    sbuilder.append_null().unwrap();
    sbuilder.append_value("hello").unwrap();
    sbuilder.append_value("add").unwrap();
    sbuilder.append_value("aaaaaa").unwrap();
    let a = sbuilder.finish();
 
    let schema = Arc::new(Schema::new(vec![
        Field::new("a", DataType::Utf8, false),
    ]));
    let batch = RecordBatch::try_new(
        schema.clone(),
        vec![
            Arc::new(a),
        ],
    ).unwrap();
 
    // print the first column:
    let firstcol = batch.column(0);
    println!("{:?}", firstcol);

//below, get single value, I don't like this , is there a simple way to do that?
    let da = firstcol.as_any();
    let da1 = da.downcast_ref::<StringArray>();
    let singlevalue3 = da1.unwrap();
    let s = singlevalue3.value(3);
    println!("{:?}",s);
}

so many steps to get a single value from this array. is there a simple way to do that? who can help me?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions