-
Notifications
You must be signed in to change notification settings - Fork 3.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
GH-34690: [Go]: Add sort indices function #34719
Draft
hermanschaaf
wants to merge
3
commits into
apache:main
Choose a base branch
from
cloudquery:sort-indices
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
package kernels | ||
|
||
import ( | ||
"bytes" | ||
"sort" | ||
|
||
"github.com/apache/arrow/go/v12/arrow" | ||
"github.com/apache/arrow/go/v12/arrow/array" | ||
"github.com/apache/arrow/go/v12/arrow/compute/internal/exec" | ||
"github.com/apache/arrow/go/v12/arrow/memory" | ||
) | ||
|
||
type SortIndicesOptions struct { | ||
NullPlacement NullPlacement `compute:"null_placement"` | ||
} | ||
|
||
func (s *SortIndicesOptions) TypeName() string { | ||
return "SortIndicesOptions" | ||
} | ||
|
||
type Order int | ||
|
||
const ( | ||
Ascending Order = iota | ||
Descending | ||
) | ||
|
||
type NullPlacement int | ||
|
||
const ( | ||
AtStart NullPlacement = iota | ||
AtEnd | ||
) | ||
|
||
func GetVectorSortingKernels() []exec.VectorKernel { | ||
var base exec.VectorKernel | ||
base.CanExecuteChunkWise = true | ||
base.OutputChunked = false | ||
outType := exec.NewOutputType(arrow.ListOf(arrow.PrimitiveTypes.Int64)) | ||
kernels := make([]exec.VectorKernel, 0) | ||
for _, ty := range primitiveTypes { | ||
base.Signature = &exec.KernelSignature{ | ||
InputTypes: []exec.InputType{exec.NewExactInput(ty)}, | ||
OutType: outType, | ||
} | ||
base.ExecFn = sortExec | ||
kernels = append(kernels, base) | ||
} | ||
return kernels | ||
} | ||
|
||
func sortExec(ctx *exec.KernelCtx, batch *exec.ExecSpan, out *exec.ExecResult) error { | ||
// Get the input array from the batch | ||
inExecVal := batch.Values[0] | ||
inArr := inExecVal.Array | ||
|
||
// Create a slice of indices, initialized to [0, 1, 2, ..., n-1] | ||
indices := make([]int, inArr.Len) | ||
for i := range indices { | ||
indices[i] = i | ||
} | ||
|
||
sz := inArr.Type.(arrow.FixedWidthDataType).Bytes() | ||
|
||
// Sort the indices slice based on the values in the input array | ||
sort.Slice(indices, func(i, j int) bool { | ||
// TODO: not sure what to do here? | ||
// compare using scalar comparison? | ||
a := inArr.Buffers[1].Buf[indices[i]*sz : (indices[i]+1)*sz] | ||
b := inArr.Buffers[1].Buf[indices[j]*sz : (indices[j]+1)*sz] | ||
return bytes.Compare(a, b) < 0 | ||
}) | ||
|
||
// Create a new array builder to build the output array | ||
builder := array.NewInt64Builder(memory.DefaultAllocator) | ||
|
||
// Add the sorted indices to the output array builder | ||
for _, index := range indices { | ||
builder.Append(int64(index)) | ||
} | ||
|
||
// Build the output array and set it in the output ExecResult | ||
outArr := builder.NewArray() | ||
out.SetMembers(outArr.Data()) | ||
|
||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
package compute | ||
|
||
import ( | ||
"context" | ||
|
||
"github.com/apache/arrow/go/v12/arrow/compute/internal/kernels" | ||
) | ||
|
||
var ( | ||
sortIndicesDoc = FunctionDoc{ | ||
Summary: "Return the indices that would sort an array", | ||
Description: "This function computes an array of indices that define a stable sort of the input array, record batch or table. By default, nNull values are considered greater than any other value and are therefore sorted at the end of the input. For floating-point types, NaNs are considered greater than any other non-null value, but smaller than null values.", | ||
ArgNames: []string{"array"}, | ||
} | ||
) | ||
|
||
type SortIndicesOptions = kernels.SortIndicesOptions | ||
|
||
// RegisterVectorSorting registers functions related to vector sorting, such as sort_indices. | ||
func RegisterVectorSorting(registry FunctionRegistry) { | ||
vf := NewVectorFunction("sort_indices", Unary(), sortIndicesDoc) | ||
vf.defaultOpts = &kernels.SortIndicesOptions{} | ||
ks := kernels.GetVectorSortingKernels() | ||
for i := range ks { | ||
if err := vf.AddKernel(ks[i]); err != nil { | ||
panic(err) | ||
} | ||
} | ||
registry.AddFunction(vf, false) | ||
} | ||
|
||
func SortIndices(ctx context.Context, opts kernels.SortIndicesOptions, input Datum) (Datum, error) { | ||
return CallFunction(ctx, "sort_indices", &opts, input) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
package compute_test | ||
|
||
import ( | ||
"context" | ||
"strings" | ||
"testing" | ||
|
||
"github.com/apache/arrow/go/v12/arrow" | ||
"github.com/apache/arrow/go/v12/arrow/array" | ||
"github.com/apache/arrow/go/v12/arrow/compute" | ||
"github.com/apache/arrow/go/v12/arrow/memory" | ||
"github.com/stretchr/testify/suite" | ||
) | ||
|
||
type SortIndicesSuite struct { | ||
suite.Suite | ||
mem *memory.CheckedAllocator | ||
|
||
valueType arrow.DataType | ||
jsonData []string | ||
expectIndices []int64 | ||
|
||
expected compute.Datum | ||
input compute.Datum | ||
|
||
ctx context.Context | ||
} | ||
|
||
func (suite *SortIndicesSuite) SetupTest() { | ||
suite.mem = memory.NewCheckedAllocator(memory.DefaultAllocator) | ||
suite.ctx = compute.WithAllocator(context.Background(), suite.mem) | ||
|
||
var err error | ||
inputChunks := make([]arrow.Array, len(suite.jsonData)) | ||
for i, data := range suite.jsonData { | ||
inputChunks[i], _, err = array.FromJSON(suite.mem, | ||
suite.valueType, strings.NewReader(data)) | ||
suite.Require().NoError(err) | ||
} | ||
|
||
exp := array.NewInt64Builder(suite.mem) | ||
exp.AppendValues(suite.expectIndices, nil) | ||
arr := exp.NewArray().Data() | ||
suite.expected = &compute.ArrayDatum{Value: arr} | ||
chunked := arrow.NewChunked(inputChunks[0].DataType(), inputChunks) | ||
suite.input = &compute.ChunkedDatum{Value: chunked} | ||
|
||
for i := range inputChunks { | ||
inputChunks[i].Release() | ||
} | ||
exp.Release() | ||
} | ||
|
||
func (suite *SortIndicesSuite) TearDownTest() { | ||
suite.expected.Release() | ||
suite.input.Release() | ||
suite.mem.AssertSize(suite.T(), 0) | ||
} | ||
|
||
func (suite *SortIndicesSuite) TestSortIndices() { | ||
result, err := compute.SortIndices(suite.ctx, | ||
compute.SortIndicesOptions{ | ||
NullPlacement: 0, | ||
}, suite.input) | ||
suite.Require().NoError(err) | ||
defer result.Release() | ||
|
||
assertDatumsEqual(suite.T(), suite.expected, result, nil, nil) | ||
} | ||
|
||
func TestSortIndicesFunctions(t *testing.T) { | ||
// base64 encoded for testing fixed size binary | ||
const ( | ||
valAba = `YWJh` | ||
valAbc = `YWJj` | ||
valAbd = `YWJk` | ||
) | ||
|
||
tests := []struct { | ||
name string | ||
data []string | ||
expect []int64 | ||
valueType arrow.DataType | ||
}{ | ||
{"simple int32", []string{`[1, 1, 0, -5, -5, -5, 255, 255]`}, []int64{3, 4, 5, 2, 0, 1, 6, 7}, arrow.PrimitiveTypes.Int32}, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Just trying to get a single simple test case to pass for now |
||
//{"uint32 with nulls", []string{`[null, 1, 1, null, null, 5]`}, arrow.PrimitiveTypes.Uint32}, | ||
//{"boolean", []string{`[true, true, true, false, false]`}, arrow.FixedWidthTypes.Boolean}, | ||
//{"boolean no runs", []string{`[true, false, true, false, true, false, true, false, true]`}, arrow.FixedWidthTypes.Boolean}, | ||
//{"float64 len=1", []string{`[1.0]`}, arrow.PrimitiveTypes.Float64}, | ||
//{"bool chunks", []string{`[true, true]`, `[true, false, null, null, false]`, `[null, null]`}, arrow.FixedWidthTypes.Boolean}, | ||
//{"float32 chunked", []string{`[1, 1, 0, -5, -5]`, `[-5, 255, 255]`}, arrow.PrimitiveTypes.Float32}, | ||
//{"str", []string{`["foo", "foo", "foo", "bar", "bar", "baz", "bar", "bar", "foo", "foo"]`}, arrow.BinaryTypes.String}, | ||
//{"large str", []string{`["foo", "foo", "foo", "bar", "bar", "baz", "bar", "bar", "foo", "foo"]`}, arrow.BinaryTypes.LargeString}, | ||
//{"str chunked", []string{`["foo", "foo", null]`, `["foo", "bar", "bar"]`, `[null, null, "baz"]`, `[null]`}, arrow.BinaryTypes.String}, | ||
//{"empty arrs", []string{`[]`}, arrow.PrimitiveTypes.Float32}, | ||
//{"empty str array", []string{`[]`}, arrow.BinaryTypes.String}, | ||
//{"empty chunked", []string{`[]`, `[]`, `[]`}, arrow.FixedWidthTypes.Boolean}, | ||
//{"fsb", []string{`["` + valAba + `", "` + valAba + `", null, "` + valAbc + `", "` + valAbd + `", "` + valAbd + `", "` + valAbd + `"]`}, &arrow.FixedSizeBinaryType{ByteWidth: 3}}, | ||
//{"fsb chunked", []string{`["` + valAba + `", "` + valAba + `", null]`, `["` + valAbc + `", "` + valAbd + `", "` + valAbd + `", "` + valAbd + `"]`, `[]`}, &arrow.FixedSizeBinaryType{ByteWidth: 3}} | ||
} | ||
|
||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
suite.Run(t, &SortIndicesSuite{ | ||
valueType: tt.valueType, | ||
jsonData: tt.data, | ||
expectIndices: tt.expect, | ||
}) | ||
}) | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@zeroshade So I've gotten this far, but the
bytes.Compare
comparison here was just to get something compiling. 😃 In reality we need to compare the scalar values represented by those bytes, I believe. (I've also only tried to make it work for int32 so far.)I'm not sure how to compare scalar values inside the array with one another? Are there existing comparators that can be used her? And is there a way to access individual items in an array, other than how I'm doing it here?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It might make sense to have a look at https://github.com/apache/arrow/blob/main/go/arrow/compute/internal/kernels/scalar_comparisons.go (which implements the less than/equals/greater than/etc.) operations at a scalar level. I'll try to take another look at this early next week but you might be able to get an idea from over there on how to tackle this.
A tricky piece to think about though is that we'd want to be able to manage passing an option to allow sorting a record batch / table by multiple columns. In that scenario I think we can learn from https://arrow.apache.org/blog/2022/11/07/multi-column-sorts-in-arrow-rust-part-1/ and the corresponding part 2 and potentially leverage similar techniques to implement the sorting here.