[Tex/LaTex] Use keywords-field for sorting biblatex bibliography

biblatexsorting

I want to create a bibliography that groups references together. I thought I could add keywords and then use \printbibliography[keyword=a] for example. To use style=numeric, I would like to sort by the keywords as well.

I know, I could add keywords for grouping and additionally add presort so that the sorting works accordingly. But I thought it would be nice to have it in one single key, so I wrote a sorting scheme which results in the following MWE:

\documentclass[11pt,a4paper]{article}
\usepackage[
    backend=biber,
    sorting=sample
]{biblatex}
\DeclareSortingScheme{sample}{
    \sort{
        \field{keywords}
    }
}
\addbibresource{mybib.bib}

\begin{document}
Filler text \autocite{b}, filler text \autocite{a}.

\printbibliography[keyword=a]
\printbibliography[keyword=b]
\end{document}

The mybib.bib looks like this:

@misc{a,
    keywords = {a},
    title = {{Keyword A}},
    author = {Myself},
    year = {2000}
}

@misc{b,
    keywords = {b},
    title = {{Keyword B}},
    author = {Myself},
    year = {2000}
}

Unfortunately, 'b' is assigned [1] while 'a' is assigned [2]. Now I guess this is somehow due to the fact that keywords is a "Separated value field" and there is no sorting defined for those kinds of fields? But I could not find anything about that, so my question is: Why doesn't it work and where is it written in the biblatex documentation that keywords can not be used for sorting?

Best Answer

A possible workaround is to use \DeclareSourcemap to copy the value of the keywords list in a different field (let us say usera) and use this field to sort the entries.

Here is the definition of the source map

\DeclareSourcemap{
  \maps[datatype=bibtex]{
    \map[overwrite]{
      \step[fieldsource=keywords]
      \step[fieldset=usera, origfieldval, final]
    }
  }
}

and

\DeclareSortingScheme{sample}{
    \sort{
        \field{usera}
    }
}

With these modifications the MWE produces:

enter image description here

Related Question